本博文的方法有点投机取巧了,新博文中采取了更通用的解法,新博文地址:[leecode]Word Break II
Word Break II
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"].
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的加强,很自然的想到了DFS,但是对于一些比较变态的例子会超时,我这里采用了一种很极端的方法:首先判断s能由dict中单词组成的必要条件。即,s中的所有字母都必须出现在dict中的单词中。如果s中存在一个字母,在dict中不存在,那么直接返回找不到即可。
虽然AC了,但是总是觉得很别扭,不过暂时没想到更好的方法。
List<String> result = new ArrayList<String>();
public List<String> wordBreak(String s, Set<String> dict) {
StringBuilder sb = new StringBuilder();
boolean hasUnexistLetter = false;
ok:for(int i = 0; i < s.length(); i++){//判断是否存在某个字母不出现在字典中
for(String str: dict){
if(str.contains(s.charAt(i)+"")){
continue ok;
}
}
hasUnexistLetter = true;
}
if(!hasUnexistLetter){
dfs(sb, s, dict);
}
return result;
}
private void dfs(StringBuilder pre,String s,Set<String> dict){
if(s == null || s.length() == 0){
result.add(new String(pre).substring(1));
return;
}
for(int i = 1 ; i <= s.length(); i++){
String str = s.substring(0, i);
if(dict.contains(str)){
pre.append(' ').append(str);
String suffix = s.substring(i);
dfs(pre, suffix, dict);
pre.delete(pre.length() - 1 - str.length(),pre.length());
}
}
}