140. Word Break II
Description
Given anon-emptystringsand a dictionarywordDictcontaining a list ofnon-emptywords, add spaces insto construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.
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"]
.
UPDATE (2017/1/4):
ThewordDictparameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Discussion
Method 1
bool tracker[from][to].
O(n^2) find words.add into tracker.
Use the tracker reconstruct result.
Method 2
dfs
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_map<string, vector<string>> tracker;
return dfs(s, wordDict, tracker);
}
private:
vector<string> dfs(string s, vector<string>& wordDict, unordered_map<string, vector<string>> &tracker) {
vector<string> rst;
if(tracker.find(s) != tracker.end()) {
return tracker[s];
}
if(0 == s.size()) {
rst.push_back("");
return rst;
}
for(auto &word : wordDict) {
vector<string> tmp;
if(checkStart(s, word)) {
cout << word << " ->" << s.substr(word.size()) << endl;
tmp = dfs(s.substr(word.size()), wordDict, tracker);
for(auto words : tmp) {
if(0 != words.size())
rst.push_back(word + " " + words);
else
rst.push_back(word);
}
}
}
tracker[s] = rst;
return rst;
}
bool checkStart(string& s, string &word) {
bool rst = true;
if(s.size() < word.size()) {
return !rst;
}
for(int loop = 0; loop < word.size(); ++loop) {
if(s[loop] != word[loop]) {
rst = false;
break;
}
}
return rst;
}
};
public List<String> wordBreak(String s, Set<String> wordDict) {
return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
}
// DFS function returns an array including all substrings derived from s.
List<String> DFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>>map) {
if (map.containsKey(s))
return map.get(s);
LinkedList<String>res = new LinkedList<String>();
if (s.length() == 0) {
res.add("");
return res;
}
for (String word : wordDict) {
if (s.startsWith(word)) {
List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
for (String sub : sublist)
res.add(word + (sub.isEmpty() ? "" : " ") + sub);
}
}
map.put(s, res);
return res;
}