Leetcode 208. 实现 Trie (前缀树)
原题链接:Leetcode 208. 实现 Trie (前缀树)
struct Node {bool isend;vector<Node*> next;Node():isend(false),next(26) {};
};class Trie {
private:Node* root;Node* searchPrefix(string word){Node* node = root;for(char ch:word){node = node->next[ch-'a'];if(node==NULL) return NULL;}return node; // 匹配成功返回node}public:Trie() {root = new Node();}void insert(string word) {Node* node = root;for(auto ch: word){if(node->next[ch-'a']==NULL){node->next[ch-'a']=new Node();}node=node->next[ch-'a'];}node->isend=true;}bool search(string word) {Node* node = searchPrefix(word);return node && node->isend;}bool startsWith(string prefix) {Node* node = searchPrefix(prefix);return node!=NULL;}
};/*** 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);*/