4ms java solution. Easy to understand.


  • 1
    F
    public List<String> wordBreak(String s, Set<String> wordDict) {
            if (s == null || s.length() == 0 || wordDict == null || wordDict.size() == 0) {
                return new ArrayList<String>();
            }
            int n = s.length();
            boolean[] dp = new boolean[n + 1];
            dp[0] = true;
            int max_length = 0;
            for (String str : wordDict) {
                max_length = Math.max(max_length, str.length());
            }
            for (int i = 1; i <= n; i++) {
                for (int j = Math.max(0, i - max_length); j < i; j++) {
                    if (dp[j] && wordDict.contains(s.substring(j, i))) {
                        dp[i] = true;
                        break;
                    }
                }
            }
            HashMap<String, List<String>> map = new HashMap<String, List<String>>();
            return DFS(s, wordDict, map, dp);
        }
        
        private List<String> DFS(String s, Set<String> wordDict, HashMap<String, List<String>> map, boolean[] dp) {
            if (map.containsKey(s)) {
                return map.get(s);
            }
            List<String> res = new ArrayList<String>();
            if (s.length() == 0) {
                return res;
            }
            if (wordDict.contains(s)) {
                res.add(s);
            }
            int end = s.length();
            for (int i = end - 1; i >= 0; i--) {
                String cur = s.substring(i, end);
                if (wordDict.contains(cur) && dp[i]) {
                    List<String> list = DFS(s.substring(0, i), wordDict, map, dp);
                    for (String str : list) {
                        res.add(str + " " + cur);
                    }
                }
            }
            map.put(s, res);
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.