Skip to content

Commit 2ddfcc8

Browse files
authored
Create 139.Word-Break_Trie.cpp
1 parent 03bf7fa commit 2ddfcc8

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
class TrieNode
3+
{
4+
public:
5+
TrieNode* next[26];
6+
bool end;
7+
TrieNode()
8+
{
9+
end = false;
10+
for (int i=0;i<26;i++)
11+
next[i] = NULL;
12+
}
13+
};
14+
TrieNode* root;
15+
int memo[300];
16+
public:
17+
bool wordBreak(string s, vector<string>& wordDict)
18+
{
19+
root = new TrieNode();
20+
for (auto word: wordDict)
21+
{
22+
TrieNode* node = root;
23+
for (auto ch: word)
24+
{
25+
if (node->next[ch-'a']==NULL)
26+
node->next[ch-'a'] = new TrieNode();
27+
node = node->next[ch-'a'];
28+
}
29+
node->end = true;
30+
}
31+
32+
return dfs(s,0);
33+
}
34+
35+
bool dfs(string&s, int cur)
36+
{
37+
if (memo[cur]==1) return false;
38+
39+
if (cur==s.size())
40+
return true;
41+
42+
TrieNode* node = root;
43+
for (int i=cur; i<s.size(); i++)
44+
{
45+
if (node->next[s[i]-'a']!=NULL)
46+
{
47+
node = node->next[s[i]-'a'];
48+
if (node->end==true && dfs(s, i+1))
49+
return true;
50+
} else
51+
{
52+
break;
53+
}
54+
}
55+
56+
memo[cur] = 1;
57+
return false;
58+
}
59+
};

0 commit comments

Comments
 (0)