题解 | #字典树的实现#

字典树的实现

https://www.nowcoder.com/practice/a55a584bc0ca4a83a272680174be113b

package main

import "strconv"

/**
 * 
 * @param operators string字符串二维数组 the ops
 * @return string字符串一维数组
*/

type Tree struct{
    node [26]*Tree
    pass int
    tot int
}

func (t *Tree) insert(word string){
    tr:=t
    for _,ch:=range []byte(word){
        if tr.node[int(ch-'a')]==nil{
            tr.node[int(ch-'a')]=&Tree{}
        }
        tr=tr.node[int(ch-'a')]
        tr.pass++
    }
    tr.tot++
}

func (t *Tree) delete(word string){
    tr:=t
    for _,ch:=range []byte(word){
        tr=tr.node[int(ch-'a')]
        tr.pass--
    }
    tr.tot--
}

func (t *Tree) search(word string)bool{
    tr:=t
    for _,ch:=range []byte(word){
        if tr.node[int(ch-'a')]==nil{
            return false
        }
        tr=tr.node[int(ch-'a')]
    }
    return tr.tot>0
}

func (t *Tree) prefixNumber(pre string)int{
    tr:=t
    for i,ch:=range []byte(pre){
        if tr.node[int(ch-'a')]==nil{
            return 0
        }
        tr=tr.node[int(ch-'a')]
        if i==len(pre)-1{
            break
        }
    }
    return tr.pass
}

func trieU( operators [][]string ) []string {
    ans:=[]string{}
    t:=&Tree{}
    for _,child:=range operators{
        x,s:=child[0],child[1]
        if x=="1"{
            t.insert(s)
        }else if x=="2"{
            t.delete(s)
        }else if x=="3"{
            res:=t.search(s)
            if res{
                ans=append(ans,"YES")
            }else{
                ans=append(ans,"NO")
            }
        }else if x=="4"{
            res:=t.prefixNumber(s)
            ans=append(ans,strconv.Itoa(res))
        }
    }
    return ans
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务