前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法(十三) 前缀树

算法(十三) 前缀树

作者头像
宇宙无敌暴龙战士之心悦大王
发布2022-01-10 11:32:16
2770
发布2022-01-10 11:32:16
举报
文章被收录于专栏:kwaikwai

来自腾讯二面555。

前缀树

子树有规律的多叉树

定义

其实就是26叉树。

操作

1,add

  • 从根开始搜索字符相应的子节点。
  • 如果子节点存在,则继续搜索下一个字符对应的子节点。
  • 如果子节点不存在,则创建对应子节点。
  • 循环上述过程。

2,update

  • 从根开始搜索字符相应的子节点。
  • 如果子节点存在,则继续搜索下一个字符对应的子节点。
  • 如果子节点不存在,则返回false。
  • 循环上述过程,到最后返回true。

代码

代码语言:javascript
复制
class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
  
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
  
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
  
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

就这。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-10-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前缀树
  • 定义
  • 操作
    • 1,add
      • 2,update
      • 代码
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档