Trie数的原理是一个根据26个小写字母确定的一个26叉树,所以主要是创建树的过程:
class TrieNode {
public:
bool isWord;
TrieNode *next[26];
TrieNode() {
for (auto &i : next) {
i = nullptr;
}
isWord = false;
}
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *cur = root;
for (char i : word) {
if (!cur->next[i - 'a']) {
cur->next[i - 'a'] = new TrieNode();
}
cur = cur->next[i - 'a'];
}
cur->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *cur = root;
for (char i : word) {
if (!cur->next[i - 'a']) {
return false;
}
cur = cur->next[i - 'a'];
}
if (!cur->isWord) {
return false;
}
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *cur = root;
for (char i : prefix) {
if (!cur->next[i - 'a']) {
return false;
}
cur = cur->next[i - 'a'];
}
return true;
}
private:
TrieNode *root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/