码迷,mamicode.com
首页 > 其他好文 > 详细

140. Word Break II

时间:2017-07-24 22:36:29      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:length   duplicate   star   not   substr   contains   ict   please   private   

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

标签:length   duplicate   star   not   substr   contains   ict   please   private   

原文地址:http://www.cnblogs.com/apanda009/p/7231190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!