From : https://leetcode.com/problems/implement-trie-prefix-tree/
Implement a trie with insert
, search
,
and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
Trie中,一个字符串,比如“ab”,它表示为
“ab”是否为一个字典中的串,即’b‘是否是结尾,要看第二行’b‘指向的第三行中的isWord是否为true。
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() : isWd(false) {
for(int i=0; i<26; i++) child[i] = NULL;
}
bool isWord() {
return isWd;
}
void setWord() {
isWd = true;
}
TrieNode *getChild(int index) {
return child[index];
}
TrieNode **getChildren() {
return child;
}
void setChild(int index) {
child[index] = new TrieNode();
}
private:
bool isWd;
TrieNode *child[26];
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string s) {
TrieNode *p = root;
int size = s.size();
for(int i=0; i<size; i++) {
if(!p->getChild(s[i]-'a')) p->setChild(s[i]-'a');
p = p->getChild(s[i]-'a');
}
p->setWord();
}
// Returns if the word is in the trie.
bool search(string key) {
TrieNode *p = root;
int size = key.size();
for(int i=0; i<size; i++) {
if(!p->getChild(key[i]-'a')) return false;
p = p->getChild(key[i]-'a');
}
return p->isWord();
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p = root;
int size = prefix.size();
for(int i=0; i<size; i++) {
if(!p->getChild(prefix[i]-'a')) return false;
p = p->getChild(prefix[i]-'a');
}
return true;
}
private:
TrieNode* root;
};