public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if (s == null || s.length() ==0) {
return true;
}
int maxLength = maxLength(wordDict);
boolean[] canBeSegemented = new boolean[s.length() + 1];
canBeSegemented[0] = true;
for (int i = 1; i <= s.length(); i++) {
canBeSegemented[i] = false;
for (int j = 1; j <= maxLength && j <= i; j++) {
if (!canBeSegemented[i - j]) {
continue;
}
String newWord = s.substring(i - j, i);
if (wordDict.contains(newWord)) {
canBeSegemented[i] = true;
break;
}
}
}
return canBeSegemented[s.length()];
}
private int maxLength (Set<String> wordDict) {
int maxLength = 0;
for (String word : wordDict) {
maxLength = Math.max(word.length(), maxLength);
}
return maxLength;
}
}
Word Break
最新推荐文章于 2025-06-03 15:43:33 发布