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;
    }
}
相关推荐
紧跟先前的步伐几秒前
Go AI Agent 实战 12|HTTP 状态码、API 错误处理与日志
开发语言·人工智能·http·ai·golang
Demon--hx6 分钟前
C++ 文件流:理解 ifstream/ofstream 与 RAII 机制
开发语言·c++
纪念 2298 分钟前
C++ stack和queue
开发语言·c++
hhb_61815 分钟前
Python异步队列实战:高效处理耗时任务
开发语言·python
weixin_4166600719 分钟前
Mermaid流程图导出到Word:SVG、PNG与清晰度如何选择?
开发语言·c#
CodeYp201922 分钟前
第6讲:模板初阶
开发语言·c++·模板
SEO_juper25 分钟前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
喜欢打篮球的普通人38 分钟前
LLVM 架构设计与原理:为什么它能取代 GCC 成为新宠
c语言·开发语言
外收内放1 小时前
FastAPI猜字谜实战(3):把每一局存成JSON
开发语言·python·学习·json·fastapi
tedcloud1231 小时前
Docker Compose 部署 Memos:从安装到备份恢复
linux·开发语言·jvm·后端·docker·容器·rust