2015年6月17日星期三

[LeetCode] Word Break

Problem:

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".

Java Code:

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        //f[i]: if s.substring(0,i) can be segmented
        //f[i] = f[x] + dict.contains(s.substring(x, i)), x>0 <i
        
        if (s == null || s.length() == 0 || dict == null || dict.size() == 0) {
            return false;
        }
        
        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 = 1; j <= i; j++) {
                    f[i] = f[i] || (f[j] && dict.contains(s.substring(j, i)));
                }
            }
        }
        
        return f[s.length()];
    }
}


没有评论:

发表评论