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"]
.
参考:http://blog.csdn.net/doc_sgl/article/details/13064739
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
45
46 |
class
Solution { public : void
wordBreakHelper(string s,unordered_set<string> &dict,set<string> &unmatched, int
mn, int
mx, vector<string> &path, vector<string> &res) { int
i = mx < s.length() ? mx : s.length(); for (; i >= mn ; i--) { string preffixstr = s.substr(0,i); if (dict.find(preffixstr) != dict.end()){ path.push_back(preffixstr); if (preffixstr.size() == s.size()) { string tmp = path[0]; for ( int
i=1; i<path.size(); i++) tmp+= " " +path[i]; res.push_back(tmp); } string suffixstr = s.substr(i); if (unmatched.find(suffixstr) == unmatched.end()) { int
oldsz = res.size(); wordBreakHelper(suffixstr,dict,unmatched,mn,mx,path,res); if (res.size() == oldsz) unmatched.insert(suffixstr); } path.pop_back(); } } } vector<string> wordBreak(string s, unordered_set<string> &dict) { // Note: The Solution object is instantiated only once. vector<string> res; if (s.size() < 1 || dict.empty()) return
res; unordered_set<string>::iterator it = dict.begin(); int
maxlen=(*it).length(), minlen=(*it).length(); for (it++; it != dict.end(); it++) if ((*it).length() > maxlen) maxlen = (*it).length(); else
if ((*it).length() < minlen) minlen = (*it).length(); set<string> unmatched; vector<string> path; wordBreakHelper(s,dict,unmatched,minlen,maxlen,path,res); return
res; } }; |
[LeetCode]Word Break II,布布扣,bubuko.com
原文:http://www.cnblogs.com/Rosanna/p/3597249.html