LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))

时间:2022-04-15 05:03:08

Implement a trie with insertsearch, and startsWith methods.

实现字典树,前面好像有道题做过类似的东西,代码如下:

 class TrieNode {
public:
// Initialize your data structure here.
TrieNode():isLeaf(false)
{
for(auto & t : dic){
t = NULL;
}
}
TrieNode * dic[];
bool isLeaf;
}; class Trie {
public:
Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
void insert(string word) {
TrieNode * p = root;
for(int i = ; i < word.size(); ++i){
int index = word[i] - 'a';
if(p->dic[index] == NULL)
p->dic[index] = new TrieNode();
p = p->dic[index];
}
p->isLeaf = true;
} // Returns if the word is in the trie.
bool search(string word) {
TrieNode * p = root;
for(int i = ; i < word.size(); ++i){
int index = word[i] - 'a';
if(p->dic[index] == NULL)
return false;
p = p->dic[index];
}
return p->isLeaf;
} // Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode * p = root;
for(int i = ; i < prefix.size(); ++i){
int index = prefix[i] - 'a';
if(p->dic[index] == NULL)
return false;
p = p->dic[index];
}
return true;
} private:
TrieNode* root;
}; // Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");