140. Word Break II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了140. Word Break II相关的知识,希望对你有一定的参考价值。

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

通过hashMap进行记忆化搜索, 不过是从单词表中走, 而非s的长度上遍历

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

  

以上是关于140. Word Break II的主要内容,如果未能解决你的问题,请参考以下文章

140. Word Break II

leetcode 140 word break II 单词拆分2

140. Word Break II

140. Word Break II

140. Word Break II

140. Word Break II