forked from gzc/CLRS
-
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
gzc
committed
Jul 30, 2017
1 parent
83c8578
commit e61c6ae
Showing
2 changed files
with
61 additions
and
1 deletion.
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
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 @@ | ||
struct TrieNode { | ||
TrieNode *nodes[26]; | ||
bool word; | ||
// Initialize your data structure here. | ||
TrieNode(): word(false) { | ||
memset(nodes, 0, sizeof(nodes)); | ||
} | ||
}; | ||
|
||
class Trie { | ||
|
||
public: | ||
Trie() { | ||
root = new TrieNode(); | ||
} | ||
|
||
// Inserts a word into the trie. | ||
void insert(const string& s) { | ||
TrieNode *tmp = root; | ||
for(char ch : s) { | ||
int index = ch - 'a'; | ||
if(tmp->nodes[index] == nullptr) { | ||
tmp->nodes[index] = new TrieNode(); | ||
} | ||
tmp = tmp->nodes[index]; | ||
} | ||
tmp->word = true; | ||
} | ||
|
||
// Returns if the word is in the trie. | ||
bool search(const string& key) const { | ||
TrieNode *tmp = root; | ||
for(char ch : key) { | ||
int index = ch - 'a'; | ||
if(tmp->nodes[index] == nullptr) { | ||
return false; | ||
} | ||
tmp = tmp->nodes[index]; | ||
} | ||
return tmp->word; | ||
} | ||
|
||
// Returns if there is any word in the trie | ||
// that starts with the given prefix. | ||
bool startsWith(const string& prefix) const { | ||
TrieNode *tmp = root; | ||
for(char ch : prefix) { | ||
int index = ch - 'a'; | ||
if(tmp->nodes[index] == nullptr) { | ||
return false; | ||
} | ||
tmp = tmp->nodes[index]; | ||
} | ||
return true; | ||
} | ||
|
||
private: | ||
TrieNode* root; | ||
}; |