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"].
public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
List<String> res = new ArrayList<String>();
if(s.length() == 0 || s == null)
return res;
recursive(s, 0, dict, "", res);
return res;
}
public void recursive(String s, int index, Set<String> dict, String string, List<String> res){
if(index >= s.length()){
res.add(string);
return;
}
StringBuilder builder = new StringBuilder();
for(int i = index; i < s.length(); i++){
builder.append(s.charAt(i));
if(dict.contains(builder.toString())){
String str = string.isEmpty() ? builder.toString() : (string + " " + builder.toString());
recursive(s, index + 1, dict, str, res);
}
}
}
}不过这里有一个比较变态的test case过不去
本文介绍了一种使用回溯算法解决字符串拆分问题的方法,通过递归地检查子串是否存在于字典中来构造所有可能的句子。
271

被折叠的 条评论
为什么被折叠?



