const int MAX = 26;
class Trie {
public:
bool isWord;
Trie* next[MAX];
/** Initialize your data structure here. */
Trie() {
isWord = false;//标记单词是否结束
memset(next,0,sizeof(next));
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* cur = this;
for(char c:word){
if(!cur->next[c-'a']){
Trie* newNext = new Trie();
cur->next[c-'a'] = newNext;
}
cur = cur->next[c-'a'];
}
cur->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* cur = this;
for(char c:word){
if(cur)
cur = cur->next[c-'a'];
else
return false;
}
return cur && cur->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* cur = this;
for(char c:prefix){
if(cur)
cur = cur->next[c-'a'];
else
return false;
}
return cur;//与search的唯一不同
}
};
/**
* 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);
*/
208. 实现 Trie (前缀树)/C++
最新推荐文章于 2021-04-14 13:12:44 发布