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;
}
int maxLength = 0;
for (String word : dict) {
maxLength = Math.max(maxLength, word.length());
}
int size = s.length();
boolean[] canBreak = new boolean[size + 1];
canBreak[0] = true;
for (int i = 1; i <= size; i++) {
canBreak[i] = false;
for (int j = 1; j <= maxLength && j <= i; j++) {
if (canBreak[i - j]) {
String word = s.substring(i - j, i);
if (dict.contains(word)) {
canBreak[i] = true;
break;
}
}
}
}
return canBreak[size];
}
}