-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathword-break-ii.cpp
More file actions
66 lines (60 loc) · 2.13 KB
/
word-break-ii.cpp
File metadata and controls
66 lines (60 loc) · 2.13 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Method 1
// (Deciding break or not break for each element.)
class Solution {
public:
void recur(string& s, unordered_set<string>& wordSet, int ind, int startInd, vector<string>& res, string& temp) {
if (ind == s.size() - 1) {
if (wordSet.find(s.substr(startInd, ind - startInd + 1)) != wordSet.end()) {
string tempcopy = temp;
tempcopy += s.substr(startInd, ind - startInd + 1);
res.push_back(tempcopy);
}
return;
}
if (wordSet.find(s.substr(startInd, ind - startInd + 1)) != wordSet.end()) {
string tempcopy = temp;
tempcopy += s.substr(startInd, ind - startInd + 1) + " ";
recur(s, wordSet, ind + 1, ind + 1, res, tempcopy);
}
recur(s, wordSet, ind + 1, startInd, res, temp);
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set <string> wordSet;
for (int i = 0; i < wordDict.size(); i++) {
wordSet.insert(wordDict[i]);
}
vector<string> res;
string temp = "";
recur(s, wordSet, 0, 0, res, temp);
return res;
}
};
// Method 2
// (Can be improved to check presence by storing in unordered_set like Method 1 instead of iterating each time.)
bool isPresent(vector<string>& dictionary, string find) {
for (int i = 0; i < dictionary.size(); i++) {
if (dictionary[i] == find)return true;
}
return false;
}
void recur(vector<string>& ans, string& temp, vector<string>& dictionary, string& s, int index) {
if (index == s.size()) {
ans.push_back(temp.substr(0, temp.size() - 1));
return;
}
for (int i = index; i < s.size(); i++) {
if (isPresent(dictionary, s.substr(index, i - index + 1))) {
string tempcopy = temp;
tempcopy += s.substr(index, i - index + 1);
tempcopy += " ";
recur(ans, tempcopy, dictionary, s, i + 1);
}
}
}
vector<string> wordBreak(string &s, vector<string> &dictionary)
{
vector<string> ans;
string temp = "";
recur(ans, temp, dictionary, s, 0);
return ans;
}