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”.
/**
* sub[i],表示s[0..i]能否分词
* @param s
* @param dict
* @return
*/
public boolean wordBreak(String s, Set<String> dict) {
int length = s.length();
boolean[] sub = new boolean[length + 1];
sub[0] = true;
for (int i = 0; i < length; i++) {
if (sub[i]) {
for (int j = i + 1; j <= length; j++) {
if (dict.contains(s.substring(i,j))) {
sub[j] = true;
}
}
}
}
return sub[length];
}