https://leetcode.com/problems/word-break/
Given A string s and a Dictionary of words dict, determine if s can segmented into a space-s Eparated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
classSolution { Public: BOOLWordbreak (stringS, unordered_set<string>&worddict) { if(s.length () = =0)return false; Vector<BOOL> Canbreak (s.length (),false); for(intI=0; I<s.length (); + +i) {if(Worddict.find (S.substr (0, i+1)) !=Worddict.end ()) {Canbreak[i]=true; Continue; } for(intPre=0;p re<i;++pre) { if(Canbreak[pre] && worddict.find (S.SUBSTR (pre+1, i-pre))! =Worddict.end ()) {Canbreak[i]=true; Break; } } } returnCanbreak[s.length ()-1]; }};
View Code
https://leetcode.com/problems/word-break-ii/
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"]
.
classSolution { Public: voidFindbreakpoint (vector<BOOL>& Canbreak,string& S, unordered_set<string>&worddict) { for(intI=0; I<s.length (); + +i) {if(Worddict.find (S.substr (0, i+1)) !=Worddict.end ()) {Canbreak[i]=true; Continue; } for(intPre=0;p re<i;++pre) { if(Canbreak[pre] && worddict.find (S.SUBSTR (pre+1, i-pre))! =Worddict.end ()) {Canbreak[i]=true; Break; } } } } voidDFS (vector<string>& Res, vector<string>& load, vector<BOOL>& Canbreak,string& S, unordered_set<string>& Worddict,intidx) {if(idx = = S.length ()-1) { stringTMP =""; for(intI=0; I<load.size ()-1; ++i) tmp + = Load[i] +" "; if(Load.size () >0) Tmp+=load[load.size ()-1]; Res.push_back (TMP); return; } for(intnx=idx+1; Nx<s.length (); + +, X) { if(Canbreak[nx] && worddict.find (S.SUBSTR (idx+1, NX-IDX))! =Worddict.end ()) {Load.push_back (s.substr (IDX+1, nx-idx)); DFS (res, load, canbreak, S, Worddict, NX); Load.pop_back (); }}} vector<string> Wordbreak (stringS, unordered_set<string>&worddict) {Vector<BOOL> Canbreak (s.length (),false); Vector<string>res; res.clear (); Vector<string>load; load.clear (); Findbreakpoint (Canbreak, S, worddict); if(Canbreak[s.length ()-1]) DFS (res, load, canbreak, S, Worddict,-1); returnRes; }};
View Code
[email protected] [139/140] Word Break & Word break II