140. Word Break II

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.

Show Company Tags
Show Tags
Show Similar Problems
public class Solution {
    private List<String> result = new ArrayList<>();
    private int maxLen = 0; 
    private StringBuilder sb = new StringBuilder();
    
    public List<String> wordBreak(String s, List<String> wordDict) {
        if (s == null || wordDict == null) return result;
        if (!canBreak(s, wordDict)) return result;
        helper(s, 0, wordDict);
        return result;
    }
    
    private boolean canBreak(String s, List<String> wordDict) {
        for (String word : wordDict) maxLen = Math.max(word.length(), maxLen);
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        // Should allow i = s.length()
        for (int i = 1; i <= s.length(); i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (i - j > maxLen) {
                    dp[i] = false;
                    break;
                }
                String temp = s.substring(j, i);
                if (dp[j] && wordDict.contains(temp)) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
    
    private void helper(String s, int start, List<String> wordDict) {
        if (start == s.length()) {
            result.add(sb.substring(0, sb.length() - 1));
            return;
        }
        // Should allow i == s.length()
        for (int i = start + 1; i <= s.length(); i++) {
            if (i - start > maxLen) {
                return;
            }
            String temp = s.substring(start, i);
            if (wordDict.contains(temp)) {
                int len1 = sb.length();
                sb.append(temp + " ");
                int len2 = sb.length();
                // New recursion start from i, not i + 1;
                helper(s, i, wordDict);
                sb.delete(len1, len2);
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s