Trie树

这篇博客介绍了Trie(字典树)数据结构,它用于高效存储和检索字符串键的集合。文章详细展示了Trie的基本操作,如插入、搜索和判断前缀,并提供了Java实现。Trie的主要应用包括自动补全和拼写检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

在这里插入图片描述

class Trie {
    static class node{
        node[] child = new node[26];
        boolean is_word = false;    //截止这个结点是否是终止单词
    }

    node root;

    public Trie() {
        root = new node();
    }

    public void insert(String word) {
        node cur = root;
        for(int i = 0;i<word.length();i++)
        {
            char ch  = word.charAt(i);
            if(cur.child[ch - 'a']==null)
            {
                cur.child[ch - 'a'] = new node();
            }
            cur = cur.child[ch - 'a'];
        }
        cur.is_word = true;
    }

    public boolean search(String word) {
        node cur = root;
        int i;
        for(i = 0;i<word.length() && cur.child[word.charAt(i) - 'a']!=null ;i++)
        {
            cur = cur.child[word.charAt(i) - 'a'];
        }
        return i == word.length() && cur.is_word;
    }

    public boolean startsWith(String prefix) {
        node cur = root;
        int i;
        for(i = 0;i<prefix.length() && cur.child[prefix.charAt(i) - 'a']!=null ;i++)
        {
            cur = cur.child[prefix.charAt(i) - 'a'];
        }
        return i == prefix.length();
    }
}

DELETION:

  • 没有找到则直接返回
  • 则最终找到的结点其标志位为真,将其置为假
  • 如果该结点无孩子,则将其删除
    • 如果有孩子意味着还有其余的单词以截止这个结点的单词(即欲删除的单词)为前缀
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值