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;
    }
}
相关推荐
Ray Liang7 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi5 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端