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"]
.
Solution1:
递归调用。但是发现会超时。故要采用第二种办法。
public List<String> wordBreak(String s, Set<String> dict) {
List<String> result = new ArrayList<String>();
breakWord(result, s, 0, dict, "");
return result;
}
public void breakWord(List<String> result, String s, int start, Set<String> dict, String word) {
if(start>=s.length()) {
result.add(word.substring(1));
return;
}
for(int i=start; i<s.length(); i++) {
String prefix = s.substring(start, i+1);
if(dict.contains(prefix)) {
String newWord = word + " " + prefix;
breakWord(result, s, i+1, dict, newWord);
}
}
}
Solution2:
动态规划。如果f[i]=true,代表s.substring(i)可以分解;反之则不能被分解。
public List<String> wordBreak(String s, Set<String> dict) {
List<String> result = new ArrayList<String>();
Boolean[] f = new Boolean[s.length()+1];
Arrays.fill(f, true); //默认从哪里都可以break,后面检查后再更新
dpWordBreak(result, f, s, 0, dict, "");
return result;
}
public void dpWordBreak(List<String> result, Boolean[] f, String s, int start, Set<String> dict, String word) {
if(start>=s.length()) {
result.add(word.substring(1)); // 去掉开头的空格
return;
}
for(int i=start; i<s.length(); i++) {
String prefix = s.substring(start, i+1);
if(dict.contains(prefix) && f[i+1]) {
String newWord = word + " " + prefix;
int beforeSize = result.size();
dpWordBreak(result, f, s, i+1, dict, newWord);
if(beforeSize == result.size()) {
//如果结果列表长度不变,说明word的i+1~n子串部分没有break成功
f[i+1] = false;
}
}
}