zoukankan      html  css  js  c++  java
  • 140 Word Break II

    给出一个字符串和一个字典,求能用字典里的单词将字符串分割的所有可能。

    Input:
    s = "catsanddog"
    wordDict = ["cat", "cats", "and", "sand", "dog"]
    Output:
    [
      "cats and dog",
      "cat sand dog"
    ]

    详情:https://leetcode.com/problems/word-break-ii/

    Java实现:

    使用深度遍历的方法,每次判断字符串是否以字典中的单词为开头,如果是开头,继续判断剩余的字符串;如果最后字符串长度为0,那么就找到了能分割字符串的单词组成。这里用一个hashMap保存中间结果,否则会超时。

    class Solution {
        public List<String> wordBreak(String s, List<String> wordDict) {
            return helper(s, wordDict, new HashMap<String, LinkedList<String>>());
        }
    
        List<String> helper(String s,List<String> wordDict,HashMap<String,LinkedList<String>> map){
            if(map.containsKey(s)){
                return map.get(s);
            }
            LinkedList<String> res = new LinkedList<>();
            if(s.length() == 0){
                res.add("");
                return res;
            }
            for(String word : wordDict){
                if(s.startsWith(word)){
                    List<String> subList = helper(s.substring(word.length()),wordDict,map);
                    for(String sub : subList){
                        res.add(word + (sub.isEmpty() ? "":" ")+ sub);
                    }
                }
            }
            map.put(s,res);
            return res;
        }
    }
    

     参考:https://www.cnblogs.com/271934Liao/p/7680586.html

  • 相关阅读:
    [HDU 4828] Grids
    约瑟夫问题合集
    [POJ 1365] Prime Land
    [POJ 3270] Cow Sorting
    [POJ 1674] Sorting by Swapping
    SGU 188.Factory guard
    POJ 2942.Knights of the Round Table (双连通)
    POJ 1236.Network of Schools (强连通)
    POJ 2186.Popular Cows (强连通)
    POJ 1734.Sightseeing trip (Floyd 最小环)
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8723735.html
Copyright © 2011-2022 走看看