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"
.
Subscribe to see which companies asked this question
看上去符合递归的特点,确实用递归也可以得出正确的结果,但是,超时,转换思路----------牛逼的思路------------循环遍历字符串到目前为止是否匹配。。。。代码如下,注释的部分是递归解法
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
// int big = Integer.MIN_VALUE;
// for(String w : wordDict){
// big = big > w.length() ? big : w.length();
// }
// return getBreak(s, wordDict,0, big);
boolean[] matches = new boolean[s.length()+1];
matches[0] = true;
for(int i = 1; i <= s.length(); i++){
for(int j = 0; j < i; j ++){
if(matches[j] && wordDict.contains(s.substring(j, i))){
matches[i] = true;
break;
}
}
}
return matches[s.length()];
}
// boolean getBreak(String s, Set<String> wordDict, int start, int big){
// boolean result = false;
// if(start >= s.length()){
// return true;
// }else{
// for(int i = start + 1; i <= start + 1 + big && i <= s.length(); i++){
// if(wordDict.contains(s.substring(start, i))){
// result = getBreak(s, wordDict,i, big);
// if(result){
// return result;
// }
// }
// }
// }
// return false;
// }
}