1 struct node{ 2 map<char, struct node*> children; 3 string word; 4 node(){ 5 word = ""; 6 } 7 }; 8 class Trie{ 9 public: 10 struct node *root = NULL; 11 Trie(){ 12 root = new struct node(); 13 } 14 void addWord(string word){ 15 struct node *cur = root; 16 for(int i = 0; i < word.length(); i++){ 17 if (cur->children.find(word[i]) == cur->children.end()) { 18 cur->children[word[i]] = new struct node(); 19 } 20 cur = cur->children[word[i]]; 21 } 22 cur->word = word; 23 } 24 bool findWord(string word){ 25 struct node *cur = root; 26 for(int i = 0; i < word.length(); i++){ 27 if(cur->children.find(word[i]) == cur->children.end()){ 28 return false; 29 } 30 cur = cur->children[word[i]]; 31 } 32 return cur->word != ""; 33 } 34 };
原文:https://www.cnblogs.com/liqiniuniu/p/10570106.html