Skip to content

Commit

Permalink
Create 139.Word-Break_Trie.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Apr 21, 2021
1 parent 03bf7fa commit 2ddfcc8
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions Trie/139.Word-Break/139.Word-Break_Trie.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class Solution {
class TrieNode
{
public:
TrieNode* next[26];
bool end;
TrieNode()
{
end = false;
for (int i=0;i<26;i++)
next[i] = NULL;
}
};
TrieNode* root;
int memo[300];
public:
bool wordBreak(string s, vector<string>& wordDict)
{
root = new TrieNode();
for (auto word: wordDict)
{
TrieNode* node = root;
for (auto ch: word)
{
if (node->next[ch-'a']==NULL)
node->next[ch-'a'] = new TrieNode();
node = node->next[ch-'a'];
}
node->end = true;
}

return dfs(s,0);
}

bool dfs(string&s, int cur)
{
if (memo[cur]==1) return false;

if (cur==s.size())
return true;

TrieNode* node = root;
for (int i=cur; i<s.size(); i++)
{
if (node->next[s[i]-'a']!=NULL)
{
node = node->next[s[i]-'a'];
if (node->end==true && dfs(s, i+1))
return true;
} else
{
break;
}
}

memo[cur] = 1;
return false;
}
};

0 comments on commit 2ddfcc8

Please sign in to comment.