字典树常用模板(不断更新

python版本

class Trie:

    def __init__(self):
        self.children={
    
    }


    def insert(self, word: str) -> None:
        cur=self.children
        for i in range(len(word)):
            if word[i] not in cur.keys():
                cur[word[i]]={
    
    }
            cur=cur[word[i]]
        cur["end"]=True


    def search(self, word: str) -> bool:
        cur=self.children
        for i in range(len(word)):
            if word[i] not in cur.keys():
                return False
            cur=cur[word[i]]
        return True if "end" in cur else False


    def startsWith(self, prefix: str) -> bool:
        cur=self.children
        for i in range(len(prefix)):
            if prefix[i] not in cur.keys():
                return False
            cur=cur[prefix[i]]
        return True


猜你喜欢

转载自blog.csdn.net/weixin_39666736/article/details/105175566
今日推荐