-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139_word_break.cc
43 lines (40 loc) · 1.03 KB
/
139_word_break.cc
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
#include <string>
#include <vector>
#include <unordered_set>
using namespace::std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dirs;
int maxlen = 0;
for (const auto& e : wordDict) {
int len = e.size();
if (!len)
continue;
dirs.insert(e);
if (len > maxlen)
maxlen = len;
}
vector<int> pos(1, 0);
for (int i = 0; i < s.size(); ++i) {
int j = pos.size();
while (j-- > 0) {
int n = i + 1 - pos[j];
if (n > maxlen)
break;
if (dirs.find(s.substr(pos[j], n)) != dirs.end()) {
pos.push_back(i + 1);
break;
}
}
}
return pos.back() == s.size();
}
};
int main()
{
Solution solu;
vector<string> dict{"a", "aa", "aaa"};
string s("aaaaaaaaaaaaaaaab");
solu.wordBreak(s, dict);
}