Java实现字典树——Tire

应用场景

在搜索引擎中搜索关键字的提示功能。
在这里插入图片描述
这个是如何进行实现的勒?当然这里讲的还是最基础的啦,他就是Trie树——字典树

字典树

功能:是一种专门处理字符串匹配的数据结构,用来解决一组字符串集合中快速查找某个字符串的问题
本质:利用字符串之间的公共前缀,将重复的前缀合并在一起
比如说对于hero, high , hit 三个字符串其字典树形状为:
在这里插入图片描述
重复利用单词的公共前缀。

字典树的基本结构及操作

一、基本数据结构及节点的基本操作

  class TrieNode{
        TrieNode[] links;   //当前层的link存储下一层的引用的数组
        final int R = 26;   //因为每一个位置最多只能时26个英文字母
        boolean isEnd;      //当前字母是否可以为单词的末尾
        public TrieNode() {
            links = new TrieNode[R];
        }
        public boolean containsKey(char ch){//判断该节点的下一位是否含有ch节点
			return links[ch - 'a'] != null;
		}
		public TrieNode get(char ch){	//判断含有该节点后,就跳到下一个位在进行判断
			return links[ch - 'a']; 
		}
		public void setIsEnd(){//该节点可以是单词的末尾
			isEnd = true;	
		}
		public boolean isEnd(){	
			return isEnd;
		}
    }

然后主类进行存储根节点即可;
在java中,节点类一般以内部类的形式进行表达。

二、字典树的操作
上面写的是单个节点应该有的数据结构及操作,我们再来看看整颗树应该具有那些操作
字典树的主要操作两个:
1. 插入单词
2. 查看单词是否在字典树中

	public class Trie {
    private TrieNode root;  //保存根节点的位置

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

    //进行插入单词
    public void insert(String word) {
        TrieNode node = root;
        char[] chars = word.toCharArray();
        for (char ch : chars) {
            if (!node.containsKey(ch))
                node.put(ch, new TrieNode());
            node = node.get(ch);
        }
        node.setEnd();
    }

    //进行单词的查询
    public boolean search(String word) {
        TrieNode node = searchPrefix(word);
        return node != null && node.isEnd();
    }

    //进行前缀的查询
    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix);
        return node != null;
    }
	//因为查询前缀和单词查询都有用到因此就单独写出来
    private TrieNode searchPrefix(String word) {
        TrieNode node = root;
        char[] chars = word.toCharArray();
        for (char ch : chars) {
            if (!node.containsKey(ch))
                return null;
            node = node.get(ch);
        }
        return node;
    }
}

然后大家在看了之后可以去leetcode练习一下
208. 实现 Trie (前缀树) leetcode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值