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;
    }
}
相关推荐
海盗猫鸥2 小时前
「C++」继承
开发语言·c++
星月心城2 小时前
八股文-JavaScript(第二天)
开发语言·javascript·ecmascript
Dillon Dong2 小时前
从C到SIMULINK: 字节/字偏移 + 位偏移实现故障与故障字保存操作
c语言·开发语言·c#
m5655bj2 小时前
如何通过 C# 将 Markdown 转换为 PDF 文档
开发语言·pdf·c#
3824278272 小时前
python:yield用法
开发语言·python
wjs20242 小时前
WSDL 总结
开发语言
YoungHong19922 小时前
C++ 硬核基础:为什么函数重载不能只看返回值?
开发语言·c++
知识中的海王2 小时前
cloudflare email 邮箱混淆/加密/解密 PHP 源码版
开发语言·php
疑惑的杰瑞2 小时前
【C】函数与数组
c语言·开发语言·算法·可变参数