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; } };
【LeetCode】Word Break II,布布扣,bubuko.com
原文:http://www.cnblogs.com/ganganloveu/p/3810992.html