class TrieNode { public: // Initialize your data structure here. TrieNode() { words=0; prefixs=0; for(int i=0;i<26;i++) edges[i]=NULL; } int words; int prefixs; TrieNode* edges[26]; }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { insertHelper(root,word,0); } // Returns if the word is in the trie. bool search(string word) { return searchHelper(root,word,0)!=0; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { return startsWithHelper(root,prefix,0)!=0; } void insertHelper(TrieNode * node,string &word,int pos) { if(pos==word.size()) { node->words++; node->prefixs++; } else { node->prefixs++; int char_code=word[pos]-'a'; if(node->edges[char_code]==NULL) node->edges[char_code]=new TrieNode(); insertHelper(node->edges[char_code],word,pos+1); } } int searchHelper(TrieNode * node,string &word,int pos) { int char_code=word[pos]-'a'; if(pos==word.size()) return node->words; else if(node->edges[char_code]==NULL) return 0; else return searchHelper(node->edges[char_code],word,pos+1); } int startsWithHelper(TrieNode * node,string &word,int pos) { int char_code=word[pos]-'a'; if(pos==word.size()) return node->prefixs; else if(node->edges[char_code]==NULL) return 0; else return startsWithHelper(node->edges[char_code],word,pos+1); } private: TrieNode* root; }; /** * 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); */
补充一个python的实现:
1 class TrieNode: 2 def __init__(self): 3 self.words = 0 4 self.prefixs = 0 5 self.edges = [None] * 26 6 7 class Trie: 8 def __init__(self): 9 self.root = TrieNode() 10 11 def insert(self,word): 12 self.insertHelper(self.root,word,0) 13 14 def search(self,word): 15 return self.searchHelper(self.root,word,0) != 0 16 17 def startsWith(self,prefix): 18 return self.startsWithHelper(self.root,prefix,0) != 0 19 20 def insertHelper(self,node,word,pos): 21 if pos == len(word): 22 node.words += 1 23 node.prefixs += 1 24 else: 25 node.prefixs += 1 26 char_code = ord(word[pos]) - 97 27 if node.edges[char_code] == None: 28 node.edges[char_code] = TrieNode() 29 self.insertHelper(node.edges[char_code],word,pos+1) 30 31 def searchHelper(self,node,word,pos): 32 if pos == len(word): 33 return node.words 34 else: 35 char_code = ord(word[pos]) - 97 36 if node.edges[char_code] == None: 37 return 0 38 else: 39 return self.searchHelper(node.edges[char_code],word,pos+1) 40 41 def startsWithHelper(self,node,word,pos): 42 if pos == len(word): 43 return node.prefixs 44 else: 45 char_code = ord(word[pos]) - 97 46 if node.edges[char_code] == None: 47 return 0 48 else: 49 return self.startsWithHelper(node.edges[char_code],word,pos+1)