Given A string s and a Dictionary of words dict, add spaces in s to construct a sentence where Each of the 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"]
.
This problem is an extension of Word break
Question: According to the given dictionary of words, ask for all possible valid splits of a string.
With Word break's experience, the problem is a lot smoother.
Suppose the string s is divided into two segments, [0,i-1], [I, n-1], and if [0, i-1] is a valid word , [I, n-1] is a valid word set , then S is a valid string. [0, I-1] in turn and [I, n-1] all may be matched separately, then get s with I for the split point is all effective segmentation.
To traverse I from 1 to n-1, it is possible to obtain the full division of S.
As with Word break, you need to record the calculated results to improve efficiency. Use map<int, vector<string>> Idx_words[k] to record all effective segmentation of the [k, n-1] substring.
map<int, vector<string>>idx_words; Vector<string> Match (stringS, unordered_set<string>& Worddict,intstartidx) {Vector<string>Res; for(inti =1; I < s.size (); i++) { stringLefts = S.substr (0, i); Unordered_set<string>::iterator Us_iter =Worddict.find (lefts); if(Us_iter! =Worddict.end ()) { intRightrlidx = i +Startidx; Vector<string>Rightv; if(Idx_words.find (RIGHTRLIDX)! =Idx_words.end ()) {Rightv=Idx_words[rightrlidx]; }Else{ stringRights = S.substr (i, s.size ()-i); Rightv=Match (Rights, Worddict, RIGHTRLIDX); IDX_WORDS[RIGHTRLIDX]=Rightv; } for(intII =0; II < rightv.size (); ii++) { stringTmps = lefts +" "+Rightv[ii]; Res.push_back (Tmps); } } } if(Worddict.find (s)! =Worddict.end ()) {Res.push_back (s); } returnRes; } Vector<string> Wordbreak (stringS, unordered_set<string>&worddict) {Vector<string>Res; Res= Match (S, Worddict,0); returnRes; }
[Leetcode] Word break II ideas for solving problems