[leetcode] 实现 Trie (前缀树)
208. 实现 Trie (前缀树) - 力扣(LeetCode)
class Trie {
public:bool isEnd; //标记一个字符串的结尾Trie* next[26]; Trie(): next(nullptr), isEnd(false) {}void insert(string word) {Trie* node = this; //字典树的第一个节点for(auto &ch : word) //往下遍历{if(node->next[ch - 'a'] == nullptr){node->next[ch - 'a'] = new Trie();}node = node->next[ch - 'a'];}node->isEnd = true;}bool search(string word) {Trie* node = this;for(auto &ch : word){node = node->next[ch - 'a'];if(node == nullptr)return false;}return node->isEnd;}bool startsWith(string prefix) {Trie* node = this;for(auto& ch : prefix){node = node->next[ch - 'a'];if(node == nullptr){return false;}}return true;}
};