classTrie(object): N = 100009 def__init__(self): self.trie = [[0] * self.N for i inrange(26)] self.count = [0] * self.N self.index = 0
definsert(self, word): """ :type word: str :rtype: None """ p = 0 for i inrange(len(word)): u = ord(word[i]) - ord('a') if self.trie[u][p] == 0: self.index += 1 self.trie[u][p] = self.index p = self.trie[u][p] self.count[p] += 1
defsearch(self, word): """ :type word: str :rtype: bool """ p = 0 for i inrange(len(word)): u = ord(word[i]) - ord('a') if self.trie[u][p] == 0: returnFalse p = self.trie[u][p] return self.count[p] != 0
defstartsWith(self, prefix): """ :type prefix: str :rtype: bool """ p = 0 for i inrange(len(prefix)): u = ord(prefix[i]) - ord('a') if self.trie[u][p] == 0: returnFalse p = self.trie[u][p] returnTrue