力扣208.实现前缀树
-
前缀树是一个每个节点存一个字母的树
- 每个节点最多有26棵子树(26个字母)
-
class Trie { bool isend; Trie* next[26]; public: Trie() { isend = false; memset(next,0,sizeof(next)); } void insert(string word) { Trie* node = this; for(char c:word) { if(node->next[c-'a'] == NULL) node->next[c-'a'] = new Trie(); node = node->next[c-'a']; } node->isend = true; } bool search(string word) { Trie* node = this; for(char c:word) { node = node->next[c-'a']; if(node == NULL) return false; } return node->isend; } bool startsWith(string prefix) { Trie* node = this; for(char c:prefix) { node = node->next[c-'a']; if(node == NULL) return false; } return true; } };