Word break II
Given a stringSAnd a dictionary of wordsDict, Add spaces inSTo construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, givenS="catsanddog",Dict=["cat", "cats", "and", "sand", "dog"].
A solution is["cats and dog", "cat sand dog"].
I divide the solution into three steps:
(1) construct a two-level vector, as shown in figure (vector <int> V)
Vector v explanation:
'T2 'and 's3' have a member-1, meaning from-1 + 1 character ('C') to the current character's Word ("cat"/"Cats ").
'D6 'has members 2 and 3, meaning from 2nd + 1 character ('s') and 3rd + 1 character ('A ') to the current character, there is a word ("Sand"/"and ")AndThere is a splitting path from the string header to the current character.
'G9' has 6 members, meaning that from 6th + 1 character ('D') to the current character's Word ("dog ")AndThere is a splitting path from the beginning of the string to the current character.
(2) reverse word search based on vector V, using Stack
(3) words are separated by spaces and saved to the result vector.
class Solution{public: vector<string> result; void printStack(stack<string> stk) { string output = ""; while(!stk.empty()) { if(output == "") output += stk.top(); else output = output + " " + stk.top(); stk.pop(); } result.push_back(output); } void check(vector<vector<int> > &v, int t, stack<string> stk, string s) { if(t == -1) { printStack(stk); return ; } else { for(vector<string>::size_type st = 0; st < v[t].size(); st ++) { stk.push(s.substr(v[t][st]+1, t-v[t][st])); check(v, v[t][st], stk, s); stk.pop(); } } } vector<vector<int> > buildv(string s, unordered_set<string> &dict) { vector<vector<int> > v(s.length()); for(string::size_type st1 = 0; st1 < s.length(); st1 ++) { for(string::size_type st2 = 0; st2 <= st1; st2 ++) { if(dict.find(s.substr(st2, st1-st2+1)) != dict.end()) { if(st2 == 0) v[st1].push_back(-1); else if(!v[st2-1].empty()) v[st1].push_back(st2-1); } } } return v; } vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<vector<int> > v = buildv(s, dict); stack<string> stk; check(v, v.size()-1, stk, s); return result; }};