Trie or Prefix Tree

一个prefix tree是存储字符串的数据结构,他每一个节点有无数个子节点,每一个节点表示一个字母。

从子节点走到相应的结尾节点,经过的字母连接起来就是相应的字符串.

在定义数据结构的时候,我们首先定义ListNode:

class ListNode:
    def __init__(self, val, flag):
        self.val = val
        self.child = {} # a map that stores all the child nodes
        self.flag = flag

我们使用一个map来存储当前节点的子节点,同时我们用一个flag来记录当前节点是不是一个字符串的结束节点。

考虑:当我们输入一个“apple”了之后,我们仍可以顺着trie寻找到“app”,但是app并不是我们插入的一个字符串,所以我们通过看flag来判断当前节点是不是一个字符串的结尾。

class ListNode:
    def __init__(self, val, flag):
        self.val = val
        self.child = {} # a map that stores all the child nodes
        self.flag = flag
class Trie:
    def __init__(self):
        self.root = ListNode("",0)

    def insert(self, word: str) -> None:
        temp = self.root # get the pointer to iterate
        for char in word:# we only have to compare n steps
            if temp.child.get(char) != None:
                temp = temp.child[char]
            else:
                new = ListNode(char, 0)
                temp.child[char] = new
                temp = new
        temp.flag = 1

    def search(self, word: str) -> bool:
        temp = self.root
        for char in word:
            if temp.child.get(char) == None:
                return False
            else:
                temp = temp.child[char]
        if temp.flag == 1:
            return True
        else:
            return False
    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        temp = self.root
        for char in prefix:
            if temp.child.get(char) == None:
                return False
            else:
                temp = temp.child[char]
        return True

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值