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"].
请参考LeetCode-Word Break 查看该题的第一个版本:判断是否可分词成功。但是这一题,不仅要判断是否可以分词,还要找到所有的分词结果。
第一题是用dp[i]表示 字符串s[0....i-1]是否可以分词成功。
为了记录是怎么分词的,我们可以用dp[i]表示 字符串s[0.....i-1]的最后一个分词word,则s[0.....i-1]的倒数第二个分词即为dp[o....i-word.length()-1]。但这种方法只能记录一种分词方法,因此有必要把 dp[i] 定义 List<String>,这样就可以表示多种分词方法,最后使用DFS搜索,找到所有的分词方法。
例如对于上面的例子: s.length()=10, 则 dp[10] = {“cat”}, dp[7]={“and”,”sand”}, dp[4]={“cats”}, dp[3]={“cat”}, dp[0]={}, 其它的都为null。
dfs搜索的时,可以从后向前,也可以从前向后,只要保证最终结果的顺序即可。下面是用的从后向前搜索。
01 | public class Solution { |
02 | public static List<String> wordBreak(String s, Set<String> dict) { |
03 | List<String> dp[] = new ArrayList[s.length()+1]; |
04 | dp[0] = new ArrayList<String>(); |
05 | for(int i=0; i<s.length(); i++){ |
07 | if( dp[i] == null ) continue; |
08 | for(String word:dict){ |
09 | int len = word.length(); |
11 | if(end > s.length()) continue; |
12 | if(s.substring(i,end).equals(word)){ |
14 | dp[end] = new ArrayList<String>(); |
21 | List<String> ans = new LinkedList<String>(); |
22 | if(dp[s.length()] == null) return ans; |
23 | ArrayList<String> tmp = new ArrayList<String>(); |
24 | dfsStringList(dp,s.length(),ans, tmp); |
28 | public static void dfsStringList(List<String> dp[],int end,List<String> res, ArrayList<String> tmp){ |
30 | String ans = tmp.get(tmp.size()-1); |
31 | for(int i=tmp.size()-2; i>=0; i--) |
32 | ans += (" " + tmp.get(i) ); |
36 | for(String str:dp[end]){ |
38 | dfsStringList(dp,end-str.length(), res, tmp); |
39 | tmp.remove(tmp.size()-1); |
当然也有其他的解法,这个只是参考,效率其实还可以。