標籤:style blog http color width strong
Word Break II
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"].
我將解分為三步:
(1)構造如所示的兩級向量(vector<vector<int> > v)
向量v解釋:
‘t2‘及‘s3‘有成員-1,意為從-1+1個字元(‘c‘)到當前字元存在詞("cat"/"cats")。
‘d6‘有成員2和3,意為從第2+1個字元(‘s‘)和第3+1個字元(‘a‘)到當前字元存在詞("sand"/"and")並且存在從字串頭到當前字元的切分路徑。
‘g9‘有成員6,意為從第6+1個字元(‘d‘)到當前字元存在詞("dog")並且存在從字串開頭到當前字元的切分路徑。
(2)基於向量v逆向尋找詞,藉助棧
(3)詞以空格隔開,存入result向量
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; }};