Description
Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.
给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词
Example
Given s = “lintcode”, dict = [“lint”, “code”].
Return true because “lintcode” can be break as “lint code”.
我的思路:动态规划题。主要找分割点。利用两个for循环。外层循环来控制待验证的字符串的长度,而用内层的循环来寻找这么一个分割点,可以把字符串分成一个单词和一个同样可分解的子字符串。同时,我们用数组记录下字符串长度递增时可分解的情况,以供之后使用,避免重复计算。
如图:从d到l 一个一个找。到c了 co,cd字典里没有,code字典里有,而且dp[j+1]==true,下标为i,则dp[i]=ture.
code是字典里有的,i代表c在s和dp数组中的下标,j代表e在S和dp数组中的下标。如果要符合题目要求的话,字典里的一些字符串拼接起来等于S,所以dp[j+1]==true。这个条件 就是让判断是否可以拼接。如找到a的时候 找到的字符串是lint.此时的j+1正好是c的下标。对应的dp[j+1]==true。说明可以拼接。 所以可以将dp[i]=true.
public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
Arrays.fill(dp,false);
dp[s.length()]=true;
// 外层循环递增长度
for(int i = s.length()-1; i >=0 ; i--){
// 内层循环寻找分割点
for(int j = i; j < s.length(); j++){
String sub = s.substring(i,j+1);
if(wordDict.contains(sub) && dp[j+1]){
dp[i] = true;
break;
}
}
}
return dp[0];
}
这个参考网址:https://segmentfault.com/a/1190000003698693
但是运行的时候 超时。。。我以为这个还不够简洁或者思路不对,换了好几个网上搜的,都是超时。。。我都要放弃这个题了,心灰意冷了。 好歹坚持了一下,又到处翻,翻到了 官网提供的标准答案:
地址:http://www.jiuzhang.com/solution/word-break
public boolean wordBreak(String s, Set<String> dict) {
// write your code here
if (s == null || s.length() == 0) {
return true;
}
int maxLength = getMaxLength(dict);
boolean[] canSegment = new boolean[s.length() + 1];
canSegment[0] = true;
for (int i = 1; i <= s.length(); i++) {
canSegment[i] = false;
for (int lastWordLength = 1;
lastWordLength <= maxLength && lastWordLength <= i;
lastWordLength++) {
if (!canSegment[i - lastWordLength]) {
continue;
}
String word = s.substring(i - lastWordLength, i);
if (dict.contains(word)) {
canSegment[i] = true;
break;
}
}
}
return canSegment[s.length()];
}
private int getMaxLength(Set<String> dict) {
int maxLength = 0;
for (String word : dict) {
maxLength = Math.max(maxLength, word.length());
}
return maxLength;
}
这个代码思路是根据长度来的。从前到后 的长度,思想是差不多的,就是写法问题。为什么 它加了一个maxLength就不会超时,这个我不理解。。。