[LeetCode]Word Break II

public class Solution {
    
    public List<String> wordBreak(String s, Set<String> wordDict) {
        return helper(s, wordDict, new HashMap<String, List<String>>());
    }
    public List<String> helper(String s, Set<String> wordDict, HashMap<String, List<String>> map) {
        if (map.containsKey(s)) {
            return map.get(s);
        }
        List<String> result = new ArrayList<String>();
        if (s.length() == 0) {
            return result;
        }
        for (String str : wordDict) {
            if (str.length() > s.length()) {
                continue;
            }
            if (str.equals(s.substring(0, str.length()))) {
                if (str.equals(s)) {
                    result.add(str);
                }
                List<String> list = helper(s.substring(str.length()), wordDict, map);
                for (String ss : list) {
                    result.add(str + " " + ss);
                }
            }
        }
        map.put(s, result);
        return result;
    }
}

 

posted @ 2015-12-06 12:19  Weizheng_Love_Coding  阅读(129)  评论(0编辑  收藏  举报