Skip to content

Commit f2d84cc

Browse files
Create word_breaks_2.cpp
1 parent 4882a4b commit f2d84cc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

word_breaks_2.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
vector<string> solve(string s, unordered_map<string, bool> &words, int i){
4+
if(i >= s.size()) return {""};
5+
6+
string word;
7+
vector<string> ans;
8+
9+
for(int j = i; j<s.size(); j++){
10+
word += s[j];
11+
if(words.find(word) == words.end()) continue;
12+
//word found
13+
auto rightPart = solve(s, words, j+1);
14+
for(auto part: rightPart){
15+
string end;
16+
if(part.size() > 0) end += " " + part;
17+
ans.push_back(word + end);
18+
}
19+
20+
}
21+
return ans;
22+
}
23+
24+
vector<string> wordBreak(string s, vector<string>& wordDict) {
25+
unordered_map<string, bool> words;
26+
for(auto i : wordDict){
27+
words[i] = 1;
28+
}
29+
return solve(s, words, 0);
30+
}
31+
};

0 commit comments

Comments
 (0)