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"
.
构造一个boolean数组来储存能够在字典中查到的字符串。
boolean数组的第一个index为额外起始点。
例如 "leetcode"
table = {false, false, false,false, true,false,false,false,true}
public static boolean wordBreak(String s, Set<String> dict){
boolean[] dp = new boolean[s.length()+1];
for(int i = 0; i < s.length()+1; i++){
for(int j = 0; j < i; j++){
if(dict.contains(s.substring(j, i))){
if(j==0) dp[i] = true;
else if(dp[j]) dp[i] = true;
}
}
}
return dp[s.length()];
}