LeetCode 208 实现Trie(前缀树)

1、看完题目感觉想要简单的实现还是很容易的,直接将每次插入的word当作字符串类型存储起来,查找字符串的时候将待查找字符串与存储的各个字符串依次用“==”比较,查找前缀的时候,对存储的各个字符串用strings.HasPrefix库函数查找前缀是否存在。方法十分暴力,但居然通过了,只是执行用时,内存消耗都不太好😭。

代码如下:

type Trie struct {
    words []string  // 当前字符串word
}


func Constructor() Trie {
    return Trie{ words: []string{} }
}


func (this *Trie) Insert(word string)  {
    this.words=append(this.words, word)
}


func (this *Trie) Search(word string) bool {
    for _, v:=range this.words{
        if v==word{ return true }
    }
    return false
}


func (this *Trie) StartsWith(prefix string) bool {
    for _, v:=range this.words{
        if strings.HasPrefix(v, prefix){ return true }
    }
    return false
}

2、总感觉这种前面这种解题方法丢掉了这道题本来出题的用意,再加上之前有自己实现过一个简单的前缀树,更感觉不应该是这样的,但一时没想起来可以按单个的字母进行存储,看过题解后恍然大悟,最后实现代码如下:

type Trie struct {
    pattern [26]*Trie
    isEnd bool
}

func Constructor() Trie {
    return Trie{}
}

func (this *Trie) Insert(word string)  {
    node:=this
    for _, v:=range word{
        t:=v-'a'
        if node.pattern[t]==nil{ 
            node.pattern[t]=&Trie{}
        }
        node=node.pattern[t]
    }
    node.isEnd=true
}

func (this *Trie) Search(word string) bool {
    node:=this.searchPrefix(word)
    return node!=nil && node.isEnd
}

func (this *Trie) StartsWith(prefix string) bool {
    return this.searchPrefix(prefix)!=nil
}

func (this *Trie) searchPrefix(prefix string) *Trie {
    node:=this
    for _, v:=range prefix{
        t:=v-'a'
        if node.pattern[t]==nil{ return nil }
        node=node.pattern[t]
    }
    return node
}

还试了一下用不同的初始化方法,但最终的运行评价来看还是在struct中直接初始化的耗时短一点,用make在Constructor进行初始化的代码如下

type Trie struct {
    pattern []*Trie
    isEnd bool
}

func Constructor() Trie {
    return Trie{
        pattern: make([]*Trie, 26),
        isEnd: false,
    }
}

func (this *Trie) Insert(word string)  {
    node:=this
    for _, v:=range word{
        t:=v-'a'
        if node.pattern[t]==nil{
            newNode:=Constructor() 
            node.pattern[t]=&newNode
        }
        node=node.pattern[t]
    }
    node.isEnd=true
}

func (this *Trie) Search(word string) bool {
    node:=this.searchPrefix(word)
    return node!=nil && node.isEnd
}

func (this *Trie) StartsWith(prefix string) bool {
    return this.searchPrefix(prefix)!=nil
}

func (this *Trie) searchPrefix(prefix string) *Trie {
    node:=this
    for _, v:=range prefix{
        t:=v-'a'
        if node.pattern[t]==nil{ return nil }
        node=node.pattern[t]
    }
    return node
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值