forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
03bf7fa
commit 2ddfcc8
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |