1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { unordered_map<string, vector<string>> map; return foo(s, wordDict, map); }
vector<string> foo(string s, unordered_set<string> &wordDict, unordered_map<string, vector<string>> &map) { if(map.find(s)!=map.end()) { return map[s]; }
vector<string> res; if(s.length()==0) { res.push_back(""); return res; }
for(string word: wordDict) { if(startsWith(s, word)) { auto subList=foo(s.substr(word.length()), wordDict, map); for(auto sub: subList) res.push_back(word+(sub.size()==0?"":" ")+sub); } } map[s]=res; return res; }
bool startsWith(string lhs, string rhs) { if(lhs.length()<rhs.length()) return false; for(int i=0;i<rhs.length(); ++i) if(lhs[i]!=rhs[i]) return false; return true; } };
|