Skip to content

Word Break II

Tim_Gao edited this page Sep 18, 2016 · 1 revision
public class Solution {
    private ArrayList<String>  wordBreakImpl(String s, Set<String> wordDict, HashMap<String, ArrayList<String>> hm){
        if (hm.containsKey(s)){
            return hm.get(s);
        }
        ArrayList<String> res = new ArrayList<>();
        if(s.length() == 0){
            res.add("");
            return res;
        }
        for (String word : wordDict){
            if(s.startsWith(word)){
                ArrayList<String> sub = wordBreakImpl(s.substring(word.length()), wordDict, hm);
                for (String substr : sub){
                    if(substr.length() == 0){
                        res.add(word);
                    } else {
                        res.add(word + " " + substr);
                    }
                }
            }
        }
        hm.put(s, res);
        return res;
    }
    public List<String> wordBreak(String s, Set<String> wordDict) {
        return wordBreakImpl(s, wordDict, new HashMap<>());
    }
}

Clone this wiki locally