Python实现Tire树
class Project(object): def __init__(self): self.node = {} self.end_char = '#' def insert(self, word): node = self.node for char in word: node = node.setdefault(char, {}) node[self.end_char] = self.end_char def search(self, word): node = self.node for char in word: if char not in node: return False node = node[char] return self.end_char in node def startWith(self, prefix): node = self.node for char in prefix: if char not in node: return False node = node[char] return True if __name__ == '__main__': t = Project() t.insert('xuexi') t.insert('duexi') t.insert('xia') print(t.search('xuexi')) print(t.startWith('zhao'))
时刻记着自己要成为什么样的人!