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;
    }
}
相关推荐
weixin_520649871 天前
WinForm数据展示组件ListView
c#
九转成圣1 天前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
SmartRadio1 天前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
laowangpython1 天前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫1 天前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch1 天前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI1 天前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn
Brendan_0011 天前
JavaScript的Stomp.over
开发语言·javascript·ecmascript
念2341 天前
f5 shape分析
开发语言·javascript·ecmascript
苍穹之跃1 天前
某量JS逆向
开发语言·javascript·ecmascript