字典树(Java实现)

本文介绍了字典树(Trie树)的数据结构,强调其利用字符串公共前缀提高查询效率的特点,并通过一个LeetCode算法题实例展示了字典树的应用,解释了如何使用Java实现字典树解决给定字符串子串匹配的问题。
摘要由CSDN通过智能技术生成

字典树又称单词查找树,Trie树,是一种树形结构,字典树的优点是利用字符串的公共前缀来提高查询效率,最大限度的减少字符串在查询过程中的字符比较次数。

(字典树的简单实现图)
字典树的简单实现

字典树的结构有三点主要规范:
1.根节点不包含任何字符
2.根节点以外的任何结点都只包含一个字符
3.每个结点的子结点所包含的字符都不相同

字典树的最基本结构实现:

 class Trie{
   
        /*
        * times用于记录该字符的存储次数(若为0说明没有存储该字符) 
        * ch数组是子结点
        * isWord用于判断到达该结点时是否查询到了一个所存储的字符串
        */
        int times;
        Trie[] ch;
        boolean isWord;
        public  Trie(){
   
            //开辟的26段内存空间分别预留给代表26个英文字符的结点对象
            ch=new Trie[26];
            times=0;
            isWord=false;
        }
    }

接下来以一道leetcode算法题为例说明字典树的基本应用

题目:给出 字符串 text 和 字符串列表 words, 返回所有的索引对 [i, j] 使得在索引对范围内的子字符串 text[i]…text[j](包括 i 和 j)属于字符串列表 words。

示例 :
输入: text = “thestoryofleetcodeandme”, words = [“story”,“fleet”,“leetcode”]
输出: [[3,7],[9,13],[10,17]]

运用字典树解题代码(Java):

class Solution {
   
    //tree为字典树的空头结点
    Trie tree =new Trie();
    Vector<int[]
字典树Java实现可以使用递归来构建。首先需要定义一个TrieNode类,其中包含一个Map用于存储子节点,以及一个布尔值表示当前节点是否是一个单词的结尾。然后,定义一个Trie类来维护根节点。在Trie类中实现insert、search和startsWith方法。 下面是一个简单的字典树Java代码实现示例: ```java class TrieNode { Map<Character, TrieNode> children; boolean isEndOfWord; public TrieNode() { children = new HashMap<>(); isEndOfWord = false; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { node = new TrieNode(); current.children.put(ch, node); } current = node; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { return false; } current = node; } return current.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode current = root; for (int i = 0; i < prefix.length(); i++) { char ch = prefix.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { return false; } current = node; } return true; } } ``` 这是一个简单的Trie字典树Java代码实现,其中包括了插入、查询和查询前缀三个常用操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值