-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 5 ms (6.50%), Space: 9.7 MB (22.44%) - LeetHub
- Loading branch information
1 parent
039afe9
commit 25fdd6b
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
class Solution { | ||
public: | ||
vector<string> wordBreak(string s, vector<string>& wordDict) { | ||
//insert all the words in the set | ||
unordered_set<string> set; | ||
vector<string> res; | ||
for(auto word:wordDict) | ||
set.insert(word); | ||
//to store the current string | ||
string curr=""; | ||
findHelper(0,s,curr,set,res); | ||
return res; | ||
} | ||
|
||
void findHelper(int ind,string s,string curr,unordered_set<string> set,vector<string>& res) | ||
{ | ||
if(ind==s.length()) | ||
{ | ||
//we have reached end | ||
curr.pop_back(); //remove the trailing space | ||
res.push_back(curr); | ||
} | ||
string str=""; | ||
for(int i=ind;i<s.length();i++) | ||
{ | ||
//get every substring and check if it exists in set | ||
str.push_back(s[i]); | ||
if(set.count(str)) | ||
{ | ||
//we have got a word in dict | ||
//explore more and get other substrings | ||
findHelper(i+1,s,curr+str+" ",set,res); | ||
} | ||
} | ||
} | ||
}; |