208. 实现 Trie (前缀树)
1 //所有实现最好写在一个类中 2 class Trie 3 { 4 public: 5 bool is_end; //是否以该单词结尾 6 Trie* son[26]; //该节点儿子的个数 7 Trie() 8 { 9 is_end = false; 10 for(int i = 0;i < 26;i ++) son[i] = NULL; 11 } 12 13 /** Inserts a word into the trie. */ 14 void insert(string word) 15 { 16 auto p = this; 17 for(auto c : word) 18 { 19 int u = c - 'a'; 20 if(p->son[u] == NULL) p->son[u] = new Trie(); 21 p = p->son[u]; 22 } 23 p->is_end = true; 24 } 25 26 /** Returns if the word is in the trie. */ 27 bool search(string word) 28 { 29 auto p = this; 30 for(auto c : word) 31 { 32 int u = c - 'a'; 33 if(p->son[u] == NULL) return false; 34 p = p->son[u]; 35 } 36 return p->is_end; 37 } 38 39 /** Returns if there is any word in the trie that starts with the given prefix. */ 40 bool startsWith(string prefix) 41 { 42 auto p = this; 43 for(auto c : prefix) 44 { 45 int u = c - 'a'; 46 if(p->son[u] == NULL) return false; 47 p = p->son[u]; 48 } 49 return true; 50 } 51 };
Mamba never out

浙公网安备 33010602011771号