[Leetcode Daily] 208. 实现 Trie (前缀树)

Description

Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

示例:

输入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 True
trie.search(“app”); // 返回 False
trie.startsWith(“app”); // 返回 True
trie.insert(“app”);
trie.search(“app”); // 返回 True

思路

前缀树是一个很经典的多叉树数据结构,特点是对于储存的每个字符串,转化为一次深度遍历,可以类比二叉搜索树。优点就是方便进行前缀模糊查询,以及实现比较简单。
一个典型的前缀树像这样:
在这里插入图片描述
这里面一共三个单词:sea,sells,she。

Definition

每个节点有下面的定义:

	class Node:
    def __init__(self,val,end):
        self.val=val
        self.end=end#Add an end flag
        self.children=[]

val代表该节点代表的字符,end表示该节点是否为一个单词的结尾。children包含该节点的所有子节点。

Insert

  1. 在每个节点检索是否有下一个字符,如果有说明该节点已存在,不需要创建。否则创建一个新节点
  2. 将当前节点指针下推一层,重复操作直到单词结束
  3. 最后将最后一个节点的end置为True

Search

顺着树往下,单词没完时,如果:

  1. 该节点没有孩子节点,即self.children==None
  2. 该节点没有匹配下一个字符的节点

返回查找失败。如果顺利查找完成,即消耗完所有单词没有出现上述异常,则:

  1. 如果最后一个节点的end是False,即查找的单词是真实存在的单词的前缀,返回False
  2. 否则返回True。

Prefix

前缀是单词的一部分但不是全部。因此主要的遍历过程和search一样。需要注意的一点是如果单词遍历完的end位是True的话,那应该输出False,因为是一个完整的单词而不是前缀。

代码

class Node:
    def __init__(self,val,end):
        self.val=val
        self.end=end#Add an end flag
        self.children=[]
class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root=Node(val="",end=False)


    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        print("----------------------------------")

        print("Insert:",word)
        cur=self.root
        for c in word:
            existflag=False
            if cur.children:
                for n in cur.children:
                    if n.val==c:#已有
                        cur=n
                        existflag=True
                        #print("Existed node:",cur.val)
                        break
            #新增
            if not existflag:
                tmp=Node(val=c,end=False)
                cur.children.append(tmp)
                cur=tmp
                #print("New Node:",cur.val)
                #insert an end flag
        #Now cur should be the tail
        cur.end=True
        

            


    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        print("----------------------------------")
        print("Search:",word)
        cur=self.root
        for c in word:
            print("Check",c,cur.val)
            if cur.children:
                checked=False
                for n in cur.children:
                    #print("Check children",n.val)
                    if n.val==c:
                        cur=n
                        checked=True
                        break
                if not checked:
                    print("Search Failed because no match children:",c,cur.val)
                    return False
            else:
                print("Search Failed because no children:",word,cur.val)
                return False
        if cur.end:#end
            #print("Search Success,end is",cur.val,cur.end)
            return True
        else:
            print("Search Failed because not end:",word)
            return False



    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        print("----------------------------------")
        print("Prefix",prefix)
        cur=self.root
        for c in prefix:
            if cur.children:
                checked=False
                for n in cur.children:
                    if n.val==c:
                        cur=n
                        checked=True
                        break
                if not checked:
                    print("Search Prefix Failed because no match children:",c,cur.val)
                    return False
            else:
                return False
        if cur.end:
            print("Prefix is total word")
            return True
        else:
            return True




# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

为了debug打了点日志。
打卡。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值