题目
思路
- 一开始想截取匹配,但是会出现个情况是有好几个都匹配,而只能匹配到第一个…怎么说,总不可能这个也整回溯吧,虽然我感觉确实要回溯才可以解了。
- 写了个回溯,核心思想没问题,就是又又又又超出时间限制了…
代码
public boolean wordBreak(String s, List<String> wordDict) {
return Back(s,wordDict,0);
}
public boolean Back(String s,List<String> wordDict,int index){
if(index==s.length()) return true;
for(int i=0;i<wordDict.size();i++){
int length = wordDict.get(i).length();
if(index+length<=s.length()) {
String temp = s.substring(index, index + length);
if(temp.equals(wordDict.get(i))){
boolean flag = Back(s,wordDict,index+length);
if(flag==true) return true;
}else continue;
}
if(i==wordDict.size()-1){
return false;
}
}
return false;
}