"""
一、题目
实现一个字典树or前缀树,包含insert、search和startswith功能
"""classNode():def__init__(self):
self.childs =[None]*26
self.isLeaf =FalseclassTrie(object):def__init__(self):"""
Initialize your data structure here.
"""
self.root = Node()definsert(self, word):"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
self.inserthelper(word, self.root)definserthelper(self, word, node):if node == Node:returniflen(word)==0:
node.isLeaf =Truereturn
index =ord(word[0])-ord('a')if node.childs[index]isNone:
node.childs[index]= Node()
self.inserthelper(word[1:], node.childs[index])defsearch(self, word):"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""return self.searchhepler(word, self.root)defsearchhepler(self, word, node):if node isNone:returnFalseiflen(word)==0:return node.isLeaf
index =ord(word[0])-ord('a')return self.searchhepler(word[1:], node.childs[index])defstartsWith(self, prefix):"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""return self.startsWithhelper(prefix, self.root)defstartsWithhelper(self, prefix, node):if node isNone:returnFalseiflen(prefix)==0:returnTrue
index =ord(prefix