您的位置:首页 > 其它

【leetcode】Word Break II

2014-07-16 18:50 447 查看
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 I的代码(详细请见/article/6614097.html),先把dp的表打出来,然后DFS搜索出字符串,后来发现这样会TLE。看了九章的题解,才有了如下思路:

递归的思想,利用一个map——Map<String, ArrayList<String>> map存放单词s和它对应的拆分字符串的列表。比如题目中的例子catsanddog在map中的对应的list就有两个元素"cats and dog"和"cat sand dog"。

因为每个字符串s如果有划分,那么一定从第一个字符开始,所以,递归每次从索引0开始,找到dict中包含的s的前缀,然后递归的探求s除去这个前缀后剩下的字符串可以被拆分成的方式,如果剩下的字符串可以被拆分,那么前缀加上剩下字符串拆分得到的结果就是最终s的拆分结果了。

还是以题目中的例子来说"catsanddog"

首先发现dict中含有前缀cat,这时递归的去找"sanddog"的拆分方式,发现可以拆分为”sand dog",最终得到s的一种拆分方式"cat sand dog";

继续循环,发现dict中含有前缀"cats",这时递归的去找"anddog"的拆分方式,发现可以拆分为"and dog",最终得到s的第二种拆分方式"cats and dog"。

代码如下:

public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
return findList(s, dict, map);
}
private List<String> findList(String s,Set<String> dict,Map<String, ArrayList<String>> map){
if(map.containsKey(s)) return map.get(s);
ArrayList<String> answerList = new ArrayList<String>();
int length = s.length();
if(length <= 0)
return answerList;

for(int i = 1;i <= length;i++){
String prefix = s.substring(0,i);
if(dict.contains(prefix)){
if(i == length)
answerList.add(prefix);
else{
List<String> temp = findList(s.substring(i), dict, map);
for(String tmp:temp){
tmp = prefix + " " + tmp;
answerList.add(tmp);
}
}
}
}
map.put(s, answerList);
return answerList;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: