- 插入一个字符串
- 查找字符串
- 查找是否字符串前缀
- 两种查找区别在于:是否isEnd
- 一次建树,多次查询
class Trie {
private:
vector<Trie *> children;
bool isEnd;
public:
/** Initialize your data structure here. */
Trie() {
children.resize(26, nullptr);
isEnd = false;
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie *node = this;
for (int i = 0; i < word.size(); i++) {
int ch = word[i] - 'a';
if (node->children[ch] == nullptr) {
node->children[ch] = new Trie();
}
node = node->children[ch];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie *node = this;
for (int i = 0; i < word.size(); i++) {
int ch = word[i] - 'a';
if (node->children[ch] == nullptr) {
return false;
}
node = node->children[ch];
}
return (node != nullptr && node->isEnd);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie *node = this;
for (int i = 0; i < prefix.size(); i++) {
int ch = prefix[i] - 'a';
if (node->children[ch] == nullptr) {
return false;
}
node = node->children[ch];
}
return (node != nullptr);
}
};
/**
* 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);
*/