Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

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”].

Solution 1: Time Limit Exceeded

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        Map<Integer, List<String>> dp = new HashMap<>();
        int n = s.length();
        List<String> tmp = new ArrayList<>();
        tmp.add("");
        dp.put(n, tmp);
        for(int i=n-1; i>=0; i--){
            List<String> list = new ArrayList<>();
            for(int j=i+1; j<=n; j++){
                String str = s.substring(i, j);
                if(wordDict.contains(str)){
                    for(String suffix : dp.get(j)){
                        list.add(str + (suffix.isEmpty() ? "" : " ") + suffix);
                    }
                }
            }
            dp.put(i, list);
        }
        return dp.get(0);
    }
}

Solution 2: Time Limit Exceeded

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        Map<Integer, List<String>> dp = new HashMap<>();
        int n = s.length();
        List<String> tmp = new ArrayList<>();
        tmp.add("");
        dp.put(n, tmp);
        for(int i=n-1; i>=0; i--){
            List<String> list = new ArrayList<>();
            String str = s.substring(i);
            for(String word : wordDict){
                if(str.startsWith(word)){
                    for(String suffix : dp.get(i+word.length())){
                        list.add(word + (suffix.isEmpty() ? "" : " ") + suffix);
                    }
                }
            }
            dp.put(i, list);
        }
        return dp.get(0);
    }
}

Solution 3:

public List<String> wordBreak(String s, Set<String> wordDict) {
    return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
}       

// DFS function returns an array including all substrings derived from s.
List<String> DFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>>map) {
    if (map.containsKey(s)) 
        return map.get(s);
        
    LinkedList<String>res = new LinkedList<String>();     
    if (s.length() == 0) {
        res.add("");
        return res;
    }               
    for (String word : wordDict) {
        if (s.startsWith(word)) {
            List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
            for (String sub : sublist) 
                res.add(word + (sub.isEmpty() ? "" : " ") + sub);               
        }
    }       
    map.put(s, res);
    return res;
}
comments powered by Disqus