-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139_Word_Break
85 lines (79 loc) · 2.42 KB
/
139_Word_Break
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
BFS MLE
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
queue<string> q;
q.push(s);
while (!q.empty()){
string current = q.front();
q.pop();
for (int i = 0; i < wordDict.size(); ++i){
if (current == wordDict[i]) return true;
if (current.substr(0, wordDict[i].size()) == wordDict[i]){
q.push(current.substr(wordDict[i].size()));
}
}
}
return false;
}
};
BFS use hashset as queue
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> q;
q.insert(s);
while (!q.empty()){
unordered_set<string> thistime = q;
for (auto it = thistime.begin(); it != thistime.end(); ++it){
string current = *it;
q.erase(*it);
for (int i = 0; i < wordDict.size(); ++i){
if (current == wordDict[i]) return true;
if (current.substr(0, wordDict[i].size()) == wordDict[i] && q.count(current.substr(wordDict[i].size())) == 0){
q.insert(current.substr(wordDict[i].size()));
}
}
}
}
return false;
}
};
DP
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp (s.size() + 1, false);
dp[0] = true;
for (int i = 1; i < dp.size(); ++i){
for (int j = 1; j <= i; ++j){
string t = s.substr(i - j, j);
if (find(wordDict.begin(), wordDict.end(), t) != wordDict.end()){
dp[i] = dp[i - j];
if (dp[i] == true) break;
}
}
}
return dp[dp.size() - 1];
}
};
DP
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp (s.size() + 1, false);
dp[0] = true;
for (int i = 1; i < dp.size(); ++i){
for (int j = 1; j <= i; ++j){
if (dp[i - j]){
string t = s.substr(i - j, j);
if (find(wordDict.begin(), wordDict.end(), t) != wordDict.end()){
dp[i] = true;
break;
}
}
}
}
return dp[dp.size() - 1];
}
};