-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139.cpp
68 lines (67 loc) · 1.87 KB
/
139.cpp
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
// dp.cpp 0ms
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if (wordDict.size() == 0)
return false;
string_view sv = s;
unordered_set<string_view> hashset(wordDict.begin(), wordDict.end());
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
for (int i = 1; i <= s.size(); ++i)
for (int j = i - 1; j >= 0; --j)
if (dp[j] &&
hashset.find(sv.substr(j, i - j)) != hashset.end()) {
dp[i] = true;
break;
}
return dp.back();
}
};
// trie+dp.cpp 3ms
class Solution2 {
struct trie {
trie() : isWord(false) {}
bool isWord;
trie* children[26] = {};
} root;
void insert(string& word) {
trie* p = &root;
for (auto ch : word) {
int offset = ch - 'a';
if (p->children[offset] == nullptr)
p->children[offset] = new trie();
p = p->children[offset];
}
p->isWord = true;
}
bool search(string_view word) {
trie* p = &root;
for (auto ch : word) {
int offset = ch - 'a';
if (p->children[offset] == nullptr)
return false;
p = p->children[offset];
}
return p->isWord;
}
bool dp(string_view s) {
vector<bool> dp(s.size() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.size(); ++i) {
for (int j = i - 1; j >= 0; --j) {
if (dp[j] && search(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp.back();
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
for (string& str : wordDict)
insert(str);
return dp(s);
}
};