hot100-49前缀树

一、题目

实现一个前缀树类,提供三个操作,

1)insert(word):插入一个单词。

2)search(word):判断单词是否完整存在于 Trie 中。

3)startsWith(prefix):判断是否存在以该前缀开头的单词。

二、思路

1、每个节点,使用定长数组实现子节点映射;isEnd=true属性表示从根节点到当前节点拼出的字符串是一个完整的词。

2、一种26叉树结构,每个节点代表一个字符,从根到某节点的路径构成一个前缀;通过 isEnd 标记该路径是否为一个完整单词的结尾。

三、代码

复制代码
class Trie {
    class TrieNode{
        TrieNode[] children;
        boolean isEnd;
        public TrieNode(){
            children = new TrieNode[26];
            isEnd = false;
        }
    }
    private TrieNode root;
    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode node = root;
        for(char c : word.toCharArray()){
            int index = c - 'a';
            if(node.children[index] == null){
                node.children[index] = new TrieNode();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        TrieNode node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }
    public TrieNode searchPrefix(String prefix){
        TrieNode node = root;
        for(char c : prefix.toCharArray()){
            int index = c - 'a';
            if(node.children[index] == null){
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}
相关推荐
basketball6161 分钟前
C++面试考点 头文件与实现文件形式
开发语言·c++
SilentSamsara2 分钟前
类型注解进阶:Union、Optional、Any 与 Callable
开发语言·python·青少年编程
历程里程碑2 分钟前
56 . 高效ET非阻塞IO服务器设计指南
java·运维·服务器·开发语言·数据结构·c++·排序算法
恣艺7 分钟前
Python 游戏开发与文件处理:PyGame + Turtle + openpyxl + python-docx + PyPDF2
开发语言·python·pygame
高林雨露14 分钟前
kotlin 相关code
开发语言·kotlin
我还记得那天18 分钟前
函数的递归调用
c语言·开发语言·visualstudio
zhangfeng113318 分钟前
ThinkPHP5 事件系统的标准最佳实践 事件系统的完整设计逻辑tags.php tags.php(事件地图)
android·开发语言·php
xyq202422 分钟前
HTML 标签简写及全称
开发语言
tongluowan00723 分钟前
数据结构 Bitmap(位图)示例 - 用户签到系统
开发语言·数据结构·bitmap·用户签到系统
就叫_这个吧23 分钟前
Java线程池应用的四种方式+线程池底层实现原理
java·开发语言