算法-Trie Tree

一、例题

在这里插入图片描述

题目都已经明目张胆的提醒我们使用Trie树了,然而我并不会,暴力法失败。。。直接看题解

二、Trie树

Trie树是一种变种多叉树。

普通的多叉树的数据结构:

    class MTreeNode {
        Type val;
        MTreeNode[] nexts;
    }
// nexts表示下一层级树的节点集合,通过数组的每个位置的指针指向每个下一层的节点。

Trie树的数据结构:

class TrieNode {
    boolean isEnd; //标记当前字符是不是一个单词的末尾
    TrieNode[] nexts; //记录下一层节点位置, 长度恒为26
}

对于小写字母的Trie树,且nexts数组恒为26,即一一对应26个字母;

isEnd是这条路径上所有单词的末尾节点都为true【如sea,seane其中a和e都是Ture】

每个单词是否存在某个字符,是通过这个单词路径上对应位置是否为null确定的

若将一个单词看做一个由字母表示的链表,那么每个字符就是一个链表节点;又因为nexts是一个节点数组,可以想象到,Trie树的结构是这样的:

[注:最后一个节点为空节点,为什么会有空节点,我也不知道,看代码应该不会存在啊?]

属性及方法定义

  1. 属性、构造方法:
		private boolean isEnd;
        private Trie[] nexts;
        /** Initialize your data structure here. */
        public Trie() {
            nexts = new Trie[26];
            isEnd = false; //默认为false,可以不写
        }
  1. 插入方法:
/** Inserts a word into the trie. */
        public void insert(String word) {
            Trie cur = this;
            for (char c: word.toCharArray()) {
                if (cur.nexts[c - 'a'] == null) {
                    //为空时才创建节点,防止重复创建
                    cur.nexts[c - 'a'] = new Trie();//在这里的时候,下一层节点的数组就已经被初始化了
                }
                cur = cur.nexts[c - 'a'];
            }
            cur.isEnd = true;
        }
        
  1. 查询单词的方法:
/** Returns if the word is in the trie. */
        public boolean search(String word) {
            Trie cur = this;
            for (char c : word.toCharArray()) {
                //路径上没有这个字符,说明这个单词不存在
                if (cur.nexts[c - 'a'] == null) return false;
                cur = cur.nexts[c - 'a'];
            }
            //因为是完整的单词,因此需要为true
            return cur.isEnd;
        }
  1. 查询前缀是否存在的方法【总体上和search()相同,但是不需要保证是一个单词】
 /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            Trie cur = this;
            for (char c : prefix.toCharArray()) {
                //和search同样的道理
                if (cur.nexts[c - 'a'] == null) return false;
                cur = cur.nexts[c - 'a'];
            }
            return true; //只是查询一个前缀,不能保证这个前缀是一个实际的单词,如测试用例中的app刚开始就不是存在的
        }

本文参考至路漫漫我不畏的题解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值