字典树的构建

前言

LeetCode 208 字典树

      每个节点的只是布尔类型,每个节点都有26个孩子节点,节点的值为在单词最后一个字母处为true,其他时候为false;如图所示单词[sea,sells,she]在字典树中保存如下:(红色节点的值为true)

1.定义数据结构

 boolean val;
    Trie[] children;

    public Trie() {
        val=false;
        children=new Trie[26];
    }

2.插入单词

  public void insert(String word) {
        Trie root=this;
        for(int i=0;i<word.length();i++){
            int index=word.charAt(i)-'a';
            //节点为null时,新建节点
            if(root.children[index]==null){
                root.children[index]=new Trie();
            }
            root=root.children[index];
        }
        //在单词结束的节点将值赋true
        root.val=true;
    }

3.搜寻是否存在单词

public Trie searchprefix(String word){
        Trie root=this;
        for(int i=0;i<word.length();i++){
            int index=word.charAt(i)-'a';
            if(root.children[i]==null){
                return null;
            }
            root=root.children[index];
        }
        return root;
    }

4.完整代码

class Trie {
    boolean val;
    Trie[] children;

    public Trie() {
        val=false;
        children=new Trie[26];
    }


    public void insert(String word) {
        Trie root=this;
        for(int i=0;i<word.length();i++){
            int index=word.charAt(i)-'a';
            //节点为null时,新建节点
            if(root.children[index]==null){
                root.children[index]=new Trie();
            }
            root=root.children[index];
        }
        //在单词结束的节点将值赋true
        root.val=true;
    }
     //查找单词
    public boolean search(String word) {
        Trie root=searchprefix(word);
        return root!=null&&root.val;

    }
    //查找前缀
    public boolean startsWith(String prefix) {
        return searchprefix(prefix)!=null;

    }
    public Trie searchprefix(String word){
        Trie root=this;
        for(int i=0;i<word.length();i++){
            int index=word.charAt(i)-'a';
            if(root.children[i]==null){
                return null;
            }
            root=root.children[index];
        }
        return root;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值