leetcode 208. Implement Trie (Prefix Tree)字典树

来源:互联网 发布:淘宝寄错东西了怎么办 编辑:程序博客网 时间:2024/06/05 16:21

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.


class Node():    def __init__(self):        self.isWord = False        self.next = {}class Trie():    def __init__(self):        self.root = Node()    def insert(self, word):        now = self.root        for c in word:            if c not in now.next :                now.next[c] = Node()            now = now.next[c]        now.isWord = True    def search(self, word):        now = self.root        for c in word:            if c not in now.next :                return False            now = now.next[c]        return now.isWord    def startsWith(self, prefix):        now = self.root        for c in prefix:            if c not in now.next:                return False            now = now.next[c]        return Trueif __name__ == '__main__':    tree = Trie()    tree.insert("ab")    print(tree.search("a"))    print(tree.search("ab"))    print(tree.startsWith("a"))    print(tree.startsWith("ab"))