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》的思路来解决分词问题。然后在根据分词表格生成可能的分词路径。
本题在生成可能的分词序列时,是从tail到head扫描的。之前我的方法是从head到tail扫描的,但是TLE 错误,有个case过不去,如下:
"aaaaaaaaaaaaaaaaaaaaaaaaaaaa...ab" ["a","aa","aaa","b"]
但是反过来扫描就ac了。说明test case 中没有形如这样的case:
"baaaaaaaaaaaaaaaaaaaaaaaaaa..aaa" ["a","aa","aaa","b"]
如果有更好的方法可以通过两种case,请不吝指教,谢谢~
public void getSegStr(int end,String cur,Set<String> dict,String s,List<String> result,int [][] record) //java { String item; for(int i=end-1; i>=0 ; i--) { item = cur; if(record[i][end]==1 && dict.contains(s.substring(i,end))) { item = s.substring(i,end)+" "+item; if(i==0) result.add(item.trim()); else getSegStr(i,item,dict,s,result,record); } } } public List<String> wordBreak(String s, Set<String> dict) { List<String> result = new ArrayList<String>(); if(s.isEmpty()) return result; if(dict.contains(s)) { result.add(s); return result; } int len = s.length(); int [][] record = new int[len+1][len+1]; for(int i=0; i<=len; i++) record[i][i]=1; for(int step=1; step<=len; step++) { for(int j=step; j<=len; j++) { int i=j-step; if(dict.contains(s.substring(i,j))) { record[i][j]=1; continue; } for(int k=i+1; k<j; k++) { if(record[i][k]==1 && record[k][j]==1) { record[i][j] = 1; break; } } } } //drawback getSegStr(s.length(),"",dict,s,result,record); return result; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/42502329