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

208. 实现 Trie (前缀树)

作者头像
CaesarChang张旭
发布2021-07-08 10:55:49
3760
发布2021-07-08 10:55:49
举报
文章被收录于专栏:悟道

请你实现 Trie 类: Trie() 初始化前缀树对象。 void insert(String word) 向前缀树中插入字符串 word 。 boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。 boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。 输入 ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] 输出 [null, null, true, false, true, null, true] 解释 Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 True trie.search("app"); // 返回 False trie.startsWith("app"); // 返回 True trie.insert("app"); trie.search("app"); // 返回 True

代码语言:javascript
复制
class TreeNode{
     TreeNode[] children;
     boolean isEnd;
    public TreeNode(){
        isEnd=false;
        children=new TreeNode[26];
    }
}
class Trie {
   TreeNode root;//根节点不存储 从他的子节点开始存
  
    public Trie() {
        root=new TreeNode();
    }
    
    public void insert(String word) {
        TreeNode cur=root;
       for(int i=0;i<word.length();i++){
           int index=word.charAt(i)-'a';
           if(cur.children[index]==null){
               cur.children[index]=new TreeNode();
               cur.children[index].isEnd=false;
           }
           cur=cur.children[index];
       }
        cur.isEnd=true;
    }
    
    public boolean search(String word) {
        TreeNode cur=find(word);
        return cur!=null&&cur.isEnd==true;
    }
    
    public boolean startsWith(String prefix) {
        TreeNode cur=find(prefix);
         return cur!=null;
    }

    public TreeNode find(String word){
         TreeNode cur=root;
            for(int i=0;i<word.length();i++){
            int index=word.charAt(i)-'a';
           if(cur.children[index]==null){
               return null;
           }
           cur=cur.children[index];
     }
            return cur;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档