• b_nk_实现Trie树(用数组记录孩子结点)


    实现一个 Trie (前缀树),包含 insert, delete, isExist, 和 prefixCount 这四个操作。

    class Node:
        def __init__(self, val) -> None:
            self.child=[None for i in range(26)]
            self.isEnd=False
            self.val=val
            self.cnt=0 #以结点val为尾巴的路径数
    class Trie:
        def __init__(self) -> None:
            self.root=Node('/')
        """
        添加word
        """
        def insert(self, word: str) -> None:
            cur=self.root
            for c in word:
                u=ord(c)-ord('a')
                if not cur.child[u]:
                    cur.child[u]=Node(c)
                cur=cur.child[u]
                cur.cnt+=1
            cur.isEnd=True
        """
        删除word
        """
        def delete(self, word: str) -> None:
            cur=self.root
            for c in word:
                u=ord(c)-ord('a')
                if not cur.child[u] or cur.child[u].cnt==0: 
                    cur.child[u]=None
                    return
                cur.child[u].cnt-=1
                cur=cur.child[u]
            cur.isEnd=False
        """
        查询word是否在字典树中
        """
        def isExist(self, word: str) -> str:
            cur=self.root
            for c in word:
                u=ord(c)-ord('a')
                if not cur.child[u]:
                    return "NO"
                cur=cur.child[u]
            return "YES" if cur.isEnd else "NO"
        """
        返回以word为前缀的单词数量
        """
        def prefixCount(self, word: str) -> int:
            cur=self.root
            for c in word:
                u=ord(c)-ord('a')
                if not cur.child[u]: return 0
                cur=cur.child[u]
            return cur.cnt
        
    class Solution:
        def trieU(self , ops ):
            trie,ans=Trie(),[]
            for op in ops:
                if op[0]=="1":   #添加
                    trie.insert(op[1])
                elif op[0]=="2": #删除
                    trie.delete(op[1])
                elif op[0]=="3": #查询是否存在
                    ans.append(trie.isExist(op[1]))
                else:            #返回以op[1]开头的单词的数量
                    ans.append(str(trie.prefixCount(op[1])))
            return ans
    
  • 相关阅读:
    iOS进阶二-KVC
    iOS进阶一OC对象的本质
    2019-01-19
    2019-01-12
    2019
    2018-12-23 随笔
    2018-12-18 随笔
    2018-12-10
    2018-12-01
    2018.11.23 随笔
  • 原文地址:https://www.cnblogs.com/wdt1/p/14092212.html
Copyright © 2020-2023  润新知