Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
继上一篇写的Word Break II,该题延用上题的结果,通过得到在判断区间(0,i)是否有解来达到,截枝的效果。不然这道题直接用DFS解的话,是会导致LTE的。
直接附上代码。
public class Solution {
public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> result = new ArrayList<String>();
if(dict==null||s==null)
return result;
boolean[] check = new boolean[s.length()+1];
check[0]=true;
for(int i=1;i<=s.length();i++){
for(int j=0;j<i;j++){
if(check[j]&&dict.contains(s.substring(j,i))){
check[i]=true;
break;
}
}
}
if(!check[check.length-1])
return result;
StringBuilder temp = new StringBuilder();
helper(s,dict,check,0,result,temp);
return result;
}
public void helper(String s, Set<String> dict, boolean[] check, int start, ArrayList<String> result, StringBuilder temp){
if(start==check.length-1){
StringBuilder inner = new StringBuilder(temp);
inner.deleteCharAt(inner.length()-1);
result.add(inner.toString());
return;
}
for(int i=start+1;i<check.length;i++){
if(check[i]&&dict.contains(s.substring(start,i))){
temp.append((s.substring(start,i))+" ");
helper(s,dict,check,i,result,temp);
temp.delete(temp.length()-(i-start+1),temp.length());
}
}
return;
}
}