139. Word Break
2016-06-29 本文已影响0人
HalcyonMoon
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) {
int len = s.length();
if(len == 0){
return false;
}
boolean f[] = new boolean[len];
for(int i = 0; i<len; i++){
for(int j = i; j>=0; j--){
if((j==0 || f[j-1]) && dict.contains(s.substring(j, i+1))){
f[i] = true;
break;
}
}
}
return f[len-1];
}
}