def__init__(self): """ Initialize your data structure here. """ self.root = TrieNode()
definsert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ p = self.root for c in word: q = p.child.get(c,None) if q isNone: p.child[c] = TrieNode() q = p.child[c] p = q p.count += 1
defsearch(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ p = self.root for c in word: q = p.child.get(c,None) if q isNone: returnFalse p = q return p.count > 0
defstartsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ p = self.root for c in prefix: q = p.child.get(c,None) if q isNone: returnFalse p = q returnTrue
# Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
// Inserts a word into the trie. voidinsert(string s) { TrieNode *p = root; for(int i = 0; i < s.size(); ++ i) { if(p -> next[s[i] - 'a'] == NULL) p -> next[s[i] - 'a'] = new TrieNode(); p = p -> next[s[i] - 'a']; } p -> is_word = true; }
// Returns if the word is in the trie. boolsearch(string key) { TrieNode *p = find(key); return p != NULL && p -> is_word; }
// Returns if there is any word in the trie // that starts with the given prefix. boolstartsWith(string prefix) { return find(prefix) != NULL; }
private: TrieNode* find(string key) { TrieNode *p = root; for(int i = 0; i < key.size() && p != NULL; ++ i) p = p -> next[key[i] - 'a']; return p; } };