Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
Output:
[
“cats and dog”,
“cat sand dog”
]
给出一个字符串s,让拆分成wordDict中所有可能单词的组合
是139题的拓展,139只需要知道有没有解,而这道题让output所有的解
思路:
例如s = “catsanddog”,直观的做法是先在wordDict中找一个单词匹配,
(1) 这时候找到了cat,
{ 取剩下的部分"sanddog",再在wordDict中找匹配的,
又找到了"sand"
{ 取剩下的"dog", 在wordDict中找到dog ,返回dog}
返回找到的“sand” + “ ” + “dog”
}
再返回cat + “sand dog"
(2) 再往下找wordDict的单词匹配,又找到了“cats”,后面重复上面的做法
注意每找到一个子字符串的solution,要memorize,因为下次可能还要用到,
比如"catsanddogsanddog", 找到第一个“sanddog”的solution后保存在hashMap里面,第二次就不用再找一次“sanddog”,直接从hashMap中取就行了。
注意点2:
if (s.length() == word.length()) {
solution.add(s);
continue; //既然单词完全匹配了,为什么不直接用break
}
例如:s=“aa”,wordDict={“aa”,“a”}
for循环到wordDict的“aa”时,完全匹配,add “aa“ to solution,
但是如果break掉,后面的”a”就不再进行匹配了,也就是说会漏掉一个"a a"的solution
C++版本:
class Solution {
public:
unordered_map<string, vector<string>> mem;
vector<string> wordBreak(string s, vector<string>& wordDict) {
if (mem.count(s)) {
return mem[s];
}
vector<string> solution;
for (string word : wordDict) {
if (s.substr(0, word.size()) != word) {
continue;
}
if (s.size() == word.size()) {
solution.push_back(word);
continue;
}
vector<string> sub_solution = wordBreak(s.substr(word.size()), wordDict);
for (string tmp : sub_solution) {
solution.push_back(word + " " + tmp);
}
}
mem[s] = solution;
return solution;
}
};
Java版本:
class Solution {
HashMap<String, List<String>> mem = new HashMap<String, List<String>>();
public List<String> wordBreak(String s, List<String> wordDict) {
if (mem.containsKey(s)) {
return mem.get(s);
}
List<String> solution = new ArrayList<>();
for (String word : wordDict) {
if (!s.startsWith(word)) {
continue;
}
if (s.length() == word.length()) {
solution.add(s);
continue;
}
List<String> subSolution = wordBreak(s.substring(word.length()),
wordDict);
for (String str : subSolution) {
StringBuilder tmpSolution = new StringBuilder();
tmpSolution.append(word).append(" ").append(str);
solution.add(tmpSolution.toString());
}
}
mem.put(s, solution);
return solution;
}
}