-
Notifications
You must be signed in to change notification settings - Fork 0
/
139.word-break.cpp
83 lines (69 loc) · 1.7 KB
/
139.word-break.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* @lc app=leetcode id=139 lang=cpp
*
* [139] Word Break
*/
// @lc code=start
class Solution
{
struct TrieNode
{
TrieNode *next[26];
bool isEnd = false;
// contructor
TrieNode()
{
for (int i = 0; i < 26; ++i)
next[i] = nullptr;
}
};
TrieNode *root;
public:
bool wordBreak(string s, vector<string> &wordDict)
{
//* given a dict -> trie
//* dfs + memo
// first, construct trie
root = new TrieNode();
for (auto &word : wordDict)
{
TrieNode *node = root;
for (auto ch : word)
{
if (node->next[ch - 'a'] == nullptr)
node->next[ch - 'a'] = new TrieNode();
node = node->next[ch - 'a'];
}
node->isEnd = true;
} //for
TrieNode *node = root;
//* use memo to record where we got wrong
vector<bool> failed(s.size() + 1, false);
return dfs(0, s, failed);
}
bool dfs(int curr, string &s, vector<bool> &failed)
{
if (failed[curr])
return false;
// at the end, then we are good
if (curr == s.size())
return true;
TrieNode *node = root;
for (int i = curr; i < s.size(); ++i)
{
if (node->next[s[i] - 'a'] != nullptr)
{
node = node->next[s[i] - 'a'];
if (node->isEnd && dfs(i + 1, s, failed))
return true;
}
else
{
failed[curr] = true;
break;
}
}
return false;
}
};
// @lc code=end