前缀树(字典树/Trie) -----Java实现

目录

一.前缀树

1.什么是前缀树

2.前缀树的举例

二.前缀树的实现 

1.前缀树的数据结构

1.插入字符串

2.查找字符串

3.查找前缀

三.词典中最长的单词

1.题目描述

2.问题分析

3.代码实现


一.前缀树

1.什么是前缀树

字典树(Trie树)是一种树形数据结构,常用于字符串的存储和查找。字典树的核心思想是利用字符串之间的公共前缀来节省存储空间和提高查询效率。它是一棵多叉树,每个节点代表一个字符串的前缀,从根节点到叶子节点的路径组成一个字符串

字典树的根节点不包含字符,每个子节点代表一个字符,从根节点到任意一个节点所经过的路径上的字符连接起来即为该节点所代表的字符串。每个节点可以存储一个或多个字符串,通常使用一个标志来标记一个节点代表的字符串是否存在。当需要在一组字符串中查找某个字符串时,可以利用字典树来实现高效的查找操作。

2.前缀树的举例

例如对字符串数组{"goog","google","bai","baidu","a"}建立前缀树,此时我们可以很清晰的看到前缀树的一些特征:

  • 根结点不保存字符
  • 前缀树是一颗多叉树
  • 前缀树的每个节点保存一个字符
  • 具有相同前缀的字符串保存在同一条路径上
  • 字符串的尾处相应的在前缀树上也有结束的标志

二.前缀树的实现 

 力扣上的208题就是实现前缀树:力扣

1.前缀树的数据结构

在写代码的时候,我偏向于用哈希表来存储结点的信息,有的也可以用数组来存储结点的信息,本质上都是一样的

public class Trie {
    Map<Character, Trie> next;
    boolean isEnd;

    public Trie() {
        this.next = new HashMap<>();
        this.isEnd = false;
    }


    public void insert(String word) {

    }

    public boolean search(String word) {
        return false;

    }

    public boolean startsWith(String prefix) {
        return false;

    }
}

1.插入字符串

    public void insert(String word) {
        Trie trie = this;//获得根结点
        for (char c : word.toCharArray()) {
            if (trie.next.get(c) == null) {//当前结点不存在
                trie.next.put(c, new Trie());//创建当前结点
            }
            trie = trie.next.get(c);//得到字符c的结点,继续向下遍历
        }
        trie.isEnd = true;

    }

2.查找字符串

    public boolean search(String word) {
        Trie trie = this;//获得根结点
        for (char c : word.toCharArray()) {
            if (trie.next.get(c) == null) {//当前结点不存在
                return false;
            }
            trie = trie.next.get(c);//得到字符c的结点,继续向下遍历
        }
        return trie.isEnd;

    }

3.查找前缀

    public boolean startsWith(String prefix) {
        Trie trie = this;//获得根结点
        for (char c : prefix.toCharArray()) {
            if (trie.next.get(c) == null) {//当前结点不存在
                return false;
            }
            trie = trie.next.get(c);//得到字符c的结点,继续向下遍历
        }
        return true;

    }

接下来是力扣上关于前缀树的一些题目

三.词典中最长的单词

1.题目描述

给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。

若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。

力扣:力扣

2.问题分析

这是一道典型的前缀树的问题,但是这一题有一些特殊的要求,返回的答案是:

1.最长的单词 2.这个单词由其他单词逐步构成  3.长度相同返回字典序小的

因此我们需要对前缀树的相关代码进行修改,把字符串一一插入的代码还是不改变的,主要修改的是查找的代码,应该在 trie.next.get(c) == null在增加一个判断为false的条件,就是每一个结点都应该有一个标志true,表示每个节点都存在一个单词,最终一步步构成最长的单词(叶子结点的单词)

3.代码实现

class Solution {
    public String longestWord(String[] words) {
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(word);
        }
        String longest = "";
        for (String word : words) {
            if (trie.search(word)) {
                if (word.length() > longest.length() || ((word.length() == longest.length()) && (word.compareTo(longest) < 0))) {
                    longest = word;
                }

            }
        }
        return longest;
    }
}
class Trie {
    Map<Character, Trie> next;
    boolean isEnd;

    public Trie() {
        this.next = new HashMap<>();
        this.isEnd = false;
    }


    public void insert(String word) {
        Trie trie = this;//获得根结点
        for (char c : word.toCharArray()) {
            if (trie.next.get(c) == null) {//当前结点不存在
                trie.next.put(c, new Trie());//创建当前结点
            }
            trie = trie.next.get(c);//得到字符c的结点,继续向下遍历
        }
        trie.isEnd = true;

    }

    public boolean search(String word) {
        Trie trie = this;//获得根结点
        for (char c : word.toCharArray()) {
            if (trie.next.get(c) == null || !trie.next.get(c).isEnd) {//当前结点不存在
                return false;
            }
            trie = trie.next.get(c);//得到字符c的结点,继续向下遍历
        }
        return trie.isEnd;

    }

}

  • 25
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 20
    评论
### 回答1: Trie字典树Java代码实现可以分为以下几部分: 1. 定义Trie节点类,包含children数组和isEndOfWord标识,用于表示是否是单词的结尾。 2. 定义Trie类,包含插入、查找和删除操作。 3. 在Trie类中实现插入操作,遍历字符串每一个字符,在Trie树中寻找对应节点,如果不存在则新建节点。 4. 在Trie类中实现查找操作,遍历字符串每一个字符,在Trie树中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则说明字符串是单词。 5. 在Trie类中实现删除操作,遍历字符串每一个字符,在Trie树中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则将其设为false,并删除空节点。 如果需要完整代码和注释请告诉我。 ### 回答2: Trie字典树)是一种常用的数据结构,用于高效地存储和查找字符串。下面是Trie字典树Java代码实现,用于返回单词。 ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 字母表的大小为26 isEndOfWord = false; } public void insert(String word) { TrieNode curr = this; for (char c : word.toCharArray()) { if (curr.children[c - 'a'] == null) { curr.children[c - 'a'] = new TrieNode(); } curr = curr.children[c - 'a']; } curr.isEndOfWord = true; } public boolean search(String word) { TrieNode node = searchPrefix(word); return node != null && node.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String prefix) { TrieNode curr = this; for (char c : prefix.toCharArray()) { if (curr.children[c - 'a'] == null) { return null; } curr = curr.children[c - 'a']; } return curr; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { root.insert(word); } public boolean search(String word) { return root.search(word); } public boolean startsWith(String prefix) { return root.startsWith(prefix); } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); trie.insert("app"); System.out.println(trie.search("apple")); // 输出:true System.out.println(trie.startsWith("app")); // 输出:true System.out.println(trie.search("banana")); // 输出:false } } ``` 以上代码中,`TrieNode`表示Trie的节点,`Trie`表示Trie树的结构。其中`TrieNode`类包含了插入单词、查找单词(完全匹配)以及查找前缀的功能。`Trie`类则是对外提供插入、查找单词和前缀的方法。 在`main`方法中,我们演示了如何使用`Trie`类来插入和查找单词。首先,我们插入了两个单词"apple"和"app"。然后分别调用`search`方法来查找"apple"和"banana",以及`startsWith`方法来查找以"app"开头的单词。最后,打印出对应的结果,即是否找到了对应的单词或前缀。 以上是Trie字典树Java代码实现,用于返回单词。 ### 回答3: Trie字典树是一种经典的数据结构,用于高效地存储和查找字符串集合。下面是一个基于JavaTrie字典树的代码实现,可以实现返回单词的功能: ```java class TrieNode { private final int ALPHABET_SIZE = 26; private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[ALPHABET_SIZE]; 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); int index = ch - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return current != null && current.isEndOfWord; } public List<String> getAllWords() { List<String> result = new ArrayList<>(); TrieNode current = root; StringBuilder sb = new StringBuilder(); getAllWordsUtil(current, sb, result); return result; } private void getAllWordsUtil(TrieNode node, StringBuilder sb, List<String> result) { if (node == null) { return; } if (node.isEndOfWord) { result.add(sb.toString()); } for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { sb.append((char)('a' + i)); getAllWordsUtil(node.children[i], sb, result); sb.deleteCharAt(sb.length() - 1); } } } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); String[] words = {"hello", "world", "java", "programming"}; for (String word : words) { trie.insert(word); } List<String> allWords = trie.getAllWords(); System.out.println("All words in trie: " + allWords); } } ``` 上述代码中,TrieNode类表示字典树的节点,包括一个指向子节点的数组和一个标记,用于表示节点是否是某个单词的结尾。Trie类封装了字典树的操作,包括插入单词、查找单词和返回所有单词的功能。在代码的主函数中,我们创建一个Trie对象并插入一些单词,然后调用getAllWords()方法返回字典树中的所有单词。最后,打印出返回的单词列表。 希望以上解答对您有所帮助,如有更多疑问,请继续追问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

允歆辰丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值