2015年6月7日星期日

[LeetCode] Word Break II

Problem:

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

Java Code:

public class Solution {
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        ArrayList<String> result = new ArrayList<String>();
        if (s == null || s.length() == 0) {
            return result;
        }
        ArrayList<String> path = new ArrayList<String>();
        
        boolean[] f = new boolean[s.length() + 1];
        f[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            if (dict.contains(s.substring(0, i))) {
                f[i] = true;
            } else {
                for (int j = 0; j < i; j++) {
                    f[i] = f[i] || (f[j] && dict.contains(s.substring(j, i)));
                }
            }
        }
        
        if (f[s.length()] == false) {
            return result;
        } 
        helper(result, path, 0, s, dict);
        return result;
    }
    
    private void helper(ArrayList<String> result, ArrayList<String> path, int start, String s, Set<String> dict) {
        if (start == s.length()) {
            StringBuilder rst = new StringBuilder();
            for (String word : path) {
                rst.append(word);
                rst.append(" ");
            }
            result.add(new String(rst.substring(0, rst.length() - 1)));
            return;
        }
        for (int end = start + 1; end <= s.length(); end++) {
            if (dict.contains(s.substring(start, end))) {
                path.add(new String(s.substring(start, end)));
                helper(result, path, end, s, dict);
                path.remove(path.size() - 1);
            }
        }
    }
}

没有评论:

发表评论