2014年2月14日星期五

LeeCode - Word Break

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

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(s==null || s.length()==0) {
            return false;
        }
        boolean split[] = new boolean[s.length()];
        for(int i=0;i<s.length();i++) {
            String sub = s.substring(0, i+1);
            split[i] = dict.contains(sub);
            if(!split[i]) {
                for(int j=0;j<i;j++) {
                    if(split[j] && dict.contains(s.substring(j+1, i+1))) {
                        split[i] = true;
                        break;
                    }
                }
            }
        }
        return split[s.length()-1];
    }
}

没有评论:

发表评论