Leetcode 208. 实现 Trie (前缀树)

135 阅读2分钟

“Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。”

今天写了二叉树的中序遍历,所以打算把热题100中关于二叉树的题,都解一遍,方便大家专项学习

一、题目描述

  • Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。请你实现 Trie 类:Trie() 初始化前缀树对象。void insert(String word) 向前缀树中插入字符串 word 。boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

二、思路分析

  • 这道题首先是建立节点,分别是26个字母的数组和一个是否是单词的变量

  • 根节点是null

  • 插入的时候判断字母有没有,没有在对应的孩子下面创建

  • 有将对应的位置给到当前位置,即向下移一位,最后记得将结果标记是单词

三、AC 代码:

class Trie {

    /**
    创建节点
     */
     class TrieNode{
         boolean isWord = false;
         TrieNode[] children;
         TrieNode(){
             children = new TrieNode[26];
         }
     }

    TrieNode root;

    public Trie() {
        /**
        根节点是NULL的
         */
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode cur = root;
        int wordLength = word.length();
        /**
        插入的时候判断字母有没有,没有在对应的孩子下面创建
        有将对应的位置给到当前位置,即向下移一位,最后记得将结果标记是单词;
         */
        for(int i = 0; i < wordLength; i++){
            char c = word.charAt(i);
            int index = c - 'a';
            //没有就创建
            if(cur.children[index] == null){
                cur.children[index] = new TrieNode();
            }
            cur = cur.children[index];
        }
        cur.isWord = true;
    }
    
    public boolean search(String word) {
        TrieNode cur = root;
        int wordLength = word.length();
        for(int i = 0; i < wordLength; i++){
            char c = word.charAt(i);
            int index = c - 'a';
            if(cur.children[index] == null){
               return false;
            }
            cur = cur.children[index];
        }
       return cur.isWord;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        int wordLength = prefix.length();
        for(int i = 0; i < wordLength; i++){
            char c = prefix.charAt(i);
            int index = c - 'a';
            if(cur.children[index] == null){
               return false;
            }
            cur = cur.children[index];
        }
       return true;
    }
}

四、总结:

  • 好了,代码撸完,我们总结一下
    • 节点的创建

    • 字符串转数组,减去'a'

    • 数组下标是0到25

    • 记得把是否为单词改为true

最后这个算法是Leetcode的第208题,是热题100里的题,去年我刷了热题100用时一个月左右,接下来我会继续更新,小伙伴可以点赞关注,如果你也在刷热题100的话,希望可以对你有一些启发!