题目:
解答:
1 class Trie { 2 private: 3 bool isEnd; 4 Trie* next[26]; 5 public: 6 Trie() 7 { 8 isEnd = false; 9 memset(next, 0, sizeof(next)); 10 } 11 12 void insert(string word) 13 { 14 Trie* node = this; 15 for (char c : word) 16 { 17 if (node->next[c-‘a‘] == NULL) 18 { 19 node->next[c-‘a‘] = new Trie(); 20 } 21 node = node->next[c-‘a‘]; 22 } 23 node->isEnd = true; 24 } 25 26 bool search(string word) 27 { 28 Trie* node = this; 29 for (char c : word) 30 { 31 node = node->next[c - ‘a‘]; 32 if (node == NULL) 33 { 34 return false; 35 } 36 } 37 return node->isEnd; 38 } 39 40 bool startsWith(string prefix) 41 { 42 Trie* node = this; 43 for (char c : prefix) 44 { 45 node = node->next[c-‘a‘]; 46 if (node == NULL) 47 { 48 return false; 49 } 50 } 51 return true; 52 } 53 };
原文:https://www.cnblogs.com/ocpc/p/12833042.html