208. 实现 Trie (前缀树)

本文详细介绍了如何实现Trie数据结构,包括插入、搜索和判断前缀的功能。通过示例展示了Trie在字符串存储和检索中的效率,并提供了具体的Java代码实现。
package com.heu.wsq.leetcode.ashe_ji_ti;

/**
 * 208. 实现 Trie (前缀树)
 * @author wsq
 * @date 2021/4/14
 * Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
 * 请你实现 Trie 类:
 * Trie() 初始化前缀树对象。
 * void insert(String word) 向前缀树中插入字符串 word 。
 * boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
 * boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
 *
 * 示例:
 * 输入
 * ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
 * [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
 * 输出
 * [null, null, true, false, true, null, true]
 *
 * 解释
 * Trie trie = new Trie();
 * trie.insert("apple");
 * trie.search("apple");   // 返回 True
 * trie.search("app");     // 返回 False
 * trie.startsWith("app"); // 返回 True
 * trie.insert("app");
 * trie.search("app");     // 返回 True
 *  
 * 链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
 */
public class Trie {
    /**
     * 该节点对应的孩子数,每个节点都可能由对应的26个英文字母对应
     */
    private Trie[] children;
    /**
     * 标志该点是否是最终节点
     */
    private boolean isEnd;

    /** Initialize your data structure here. */
    public Trie() {
        this.children = new Trie[26];
        this.isEnd = false;
    }

    /**
     * 前缀树一般分为两个操作:插入和查询
     * 字符串插入的思想可分为两步:
     * 1.从root匹配子节点,如果没有对应的子节点,就创建新节点,并与root节点相连,转到步骤3
     * 2.如果有对应的子节点,直接转到步骤3
     * 3.继续沿着对应的子节点进行插入
     * @param word
     */
    public void insert(String word) {
        // 插入有两种情况
        // 1.已存在对应节点
        // 2.不存在对应节点
        char[] arr = word.toCharArray();
        Trie trie = this;
        for(char c: arr){
            int pos = c - 'a';
            if (trie.children[pos] == null){
                trie.children[pos] = new Trie();
            }
            trie = trie.children[pos];
        }
        trie.isEnd = true;
    }

    /**
     * 查询操作,就是查询一个字符串S是不是在集合中。
     * 如果字符串S在该树中,则能完成字符串的全部匹配,
     * 且最后一个节点的isEnd属性是true,表示插入了对应字符串
     * @param word
     * @return
     */
    public boolean search(String word) {
        // 搜索字符串是否存在
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie node = searchPrefix(prefix);
        return node != null;
    }

    private Trie searchPrefix(String word){
        int n = word.length();
        Trie node = this;
        for(int i = 0; i < n; i++){
            char c = word.charAt(i);
            int pos = c - 'a';
            if(node.children[pos] == null){
                return null;
            }
            node = node.children[pos];
        }
        return node;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值