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"
.
我做这道题的思想是,对于词典中的每一个词,如果跟当前的string的前面是相同的。那么看看剩下的string能不能被分割。
如果剩下的能被切割,直接返回true。
如果对于所有匹配的词,剩下的string都不能被分割了。那么返回false。
同时为了开辟一个数组canReach,用于标记以某个index开始的剩下的string是不是能被分割。这样能够避免大量的重复计算。
也是很动态规划的思想。
运行时间:
代码:
public class WordBreak {
public boolean wordBreak(String s, Set<String> wordDict) {
int[] canReach = new int[s.length()];
Arrays.fill(canReach, Integer.MAX_VALUE);
return doWordBeak(s, 0, wordDict, canReach);
}
private boolean doWordBeak(String s, int begin, Set<String> wordDict, int[] canReach) {
if (begin == s.length()) {
return true;
} else if (begin > s.length()) {
return false;
}
if (canReach[begin] == 1) {
return true;
}
else if (canReach[begin] == -1) {
return false;
}
for (String word : wordDict) {
if (begin + word.length() <= s.length()) {
if (s.substring(begin, begin + word.length()).compareTo(word) == 0) {
if (doWordBeak(s, begin + word.length(), wordDict, canReach)) {
canReach[begin] = 1;
return true;
}
}
}
}
canReach[begin] = -1;
return false;
}
}