leetcode—实现Trie(前缀树)

1 题目描述

Trie发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word 。
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

2 前缀树

字典树:又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高

leetcode—实现Trie(前缀树)_第1张图片

leetcode—实现Trie(前缀树)_第2张图片 

 

3 代码

class Trie {

    // 私有成员变量 表示当前前缀树的子节点数组,用于存储26个字母的子节点
    private Trie[] children;
    // 表示当前节点是否是单词的结尾
    private boolean isEnd;

    // 构造函数 初始化子节点数组和isEnd变量
    public Trie() {
        // 初始化子节点数组
        children = new Trie[26];
        isEnd = false;
    }
    
    // 插入单词树
    public void insert(String word) {
        // 获取当前节点 (根节点)
        Trie node = this;
        // 遍历所要插入的单词 的每个字符
        for(int i = 0; i < word.length(); i++){
            // 获取当前字符
            char ch = word.charAt(i);
            // 获取当前字符在字母表中的索引
            int index = ch - 'a';
            // 如果子节点数组汇总没有该索引的子节点,则新建一个
            if(node.children[index] == null){
                node.children[index] = new Trie();
            }
            // 更新当前节点 为该索引的子节点
            node = node.children[index];
        }
        // 将当前节点的isEnd属性设置为true,表示是一个单词的索引
        node.isEnd = true;
    }
    
    // 查找指定单词是否在前缀树中
    public boolean search(String word) {
        // 调用searchPrefix方法 
         Trie node = searchPrefix(word);
         // node不为null 并且当前节点表示最后一个节点,则返回true,否则 则返回false
         return node != null && node.isEnd;
    }
    
    // 检查指定前缀是否存在
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    // 公共的方法 用于搜索给定单词为前缀的方法
    private Trie searchPrefix(String prefix){
        // 当前节点
        Trie node = this;
        // 遍历前缀的每个字符
        for(int i = 0; i < prefix.length(); i++){
            // 获取当前字符以及在字母表中的索引
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            
            // 若当前索引不在前缀树中 返回null 
            if(node.children[index] == null){
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

 

你可能感兴趣的:(leetcode,算法,职场和发展,java,数据结构)