Given a string s and a dictionary of words dict, determine ifs 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"
.
[分析]
认真读题。。这道题绝对不是对半分的意思。。。要有同时满足一个string分成好几段的觉悟。
动态规划!
public class Solution {
private int getMaxLength(Set<String> dict) { //返回dict里面最到的字符串的长度。 [aaa,aa] -> 3
int maxLength = 0;
for (String word : dict) {
maxLength = Math.max(maxLength, word.length());
}
return maxLength;
}
public boolean wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) { //如果字符串为空,或者长度为零,返回真值。
return true;
}
int maxLength = getMaxLength(dict); //调用getMaxLength, 得到dict中元素长度最长长度
boolean[] canSegment = new boolean[s.length() + 1]; //用来记录每个元素位置是否可分
canSegment[0] = true; //第一个位置记录为可分
for (int i = 1; i <= s.length(); i++) { //遍历整个string
canSegment[i] = false; //先假设位置时不可分的
for (int j = 1; j <= maxLength && j <= i; j++) {
if (!canSegment[i - j]) { //从长度为1开始到end,屡过来,如果前面有可分得再看看后面的substring,如果也可分,那么i这个地方就是可以分得。
continue; //这样子也可以保证能得到很多组解
}
String word = s.substring(i - j, i);
if (dict.contains(word)) {
canSegment[i] = true;
break;
}
}
}
return canSegment[s.length()];
}
}