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"]
.
DPsolution 0ms:
class Solution { public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<string> res; int n = s.size(); if(!n || wordDict.empty()) return res; int longestWord = 0; for(auto w:wordDict){ longestWord = max(longestWord, int(w.size())); } vector<bool> D(n+1,false); D[0]= true; for(int i=n-1; i>=0; i--){ if(wordDict.find(s.substr(i))!=wordDict.end()) break; if(i==0) return res; } vector<vector<string>> index(n+1,vector<string>()); for(int i=1; i<=n; i++){ for(int j=i-1; j>=max(0,i-longestWord); j--){ if(D[j]){ string t = s.substr(j,i-j); if(wordDict.find(t)!=wordDict.end()){ D[i] = true; if(j==0){ index[i].push_back(t); } else for(auto w:index[j]){ index[i].push_back(w+' '+t); } } } } } return index[n]; } };
class Solution { public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<string> res; int n = s.size(); if(!n || wordDict.empty()) return res; int longestWord = 0; for(auto w:wordDict){ longestWord = max(longestWord, int(w.size())); } vector<bool> D(n+1,false); D[0]= true; for(int i=1; i<=n; i++){ for(int j=i-1; j>=max(0,i-longestWord); j--){ if(D[j]){ string t = s.substr(j,i-j); if(wordDict.find(t)!=wordDict.end()){ D[i] = true; break; } } } } if(!D[n]) return res; string temp; getres(s,temp,res,D,wordDict,n); return res; } void getres(string s, string temp, vector<string>& res, vector<bool>& D,unordered_set<string>& wordDict,int end){ if(end==0){ res.push_back(temp.substr(0,temp.size()-1)); return; } for(int i=end-1; i>=0; i--){ if(D[i]){ string t = s.substr(i,end-i); if(wordDict.find(t)!=wordDict.end()){ string temp1 = temp; temp = t + ' ' + temp; getres(s,temp,res,D,wordDict,i); temp = temp1; } } } } };