implement a trie with
insert
, search
, and startsWith
methods.Note:
You may assume that all inputs are consist of lowercase letters a-z
.
1 class Trie: 2 3 def __init__(self): 4 """ 5 Initialize your data structure here. 6 """ 7 self.end = False 8 self.c = {} 9 10 11 def insert(self, word): 12 """ 13 Inserts a word into the trie. 14 :type word: str 15 :rtype: void 16 """ 17 node = self 18 for w in word: 19 if w not in node.c: 20 node.c[w] = Trie() 21 node = node.c[w] 22 node.end = True 23 24 25 def prefixnode(self, word): 26 node = self 27 for w in word: 28 if w not in node.c: 29 return None 30 node = node.c[w] 31 return node 32 def search(self, word): 33 """ 34 Returns if the word is in the trie. 35 :type word: str 36 :rtype: bool 37 """ 38 node = self.prefixnode(word) 39 if not node: 40 return False 41 else: 42 if node.end: 43 return True 44 else: 45 return False 46 47 def startsWith(self, prefix): 48 """ 49 Returns if there is any word in the trie that starts with the given prefix. 50 :type prefix: str 51 :rtype: bool 52 """ 53 node = self.prefixnode(prefix) 54 return node is not None 55 56 57 58 # Your Trie object will be instantiated and called as such: 59 # obj = Trie() 60 # obj.insert(word) 61 # param_2 = obj.search(word) 62 # param_3 = obj.startsWith(prefix)