前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法:字典树(Trie)-理论与实战

算法:字典树(Trie)-理论与实战

作者头像
营琪
发布2019-11-04 16:33:01
6470
发布2019-11-04 16:33:01
举报
文章被收录于专栏:营琪的小记录

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/weixin_43126117/article/details/100660099

回想我们百度一下的过程,输入几个单词后,自动搜索出可能的选择,当没有完全匹配的搜索结果,可以返回前缀最相似的可能。 这个功能实现原理是上面呢?

字典树

这个功能的原理是字典树,通过匹配前缀,再通过一些内部算法,达到相似的可能,再输出给我们选择。

字典树 是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。

类似的应用场景

字典树的实现

leetcode:208实现 Trie (前缀树)

代码语言:javascript
复制
​class Trie {
    class TrieNode {
        char value;
        TrieNode[] childer;
        Boolean isEng = false;   //下面是否有节点

        public TrieNode(char c) {
            this.value = c;
            childer = new TrieNode[26];//仅限26个小写之母
        }
    }

    TrieNode root;

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        root = new TrieNode('/');
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {      //插入
        TrieNode p = root;
/*        for (int i = 0; i < word.length(); i++) {
//            if (p.childer[word.length() - 'a'] == word.charAt(i))
            if (p.childer[word.charAt(i) - 'a'] == null) {
                p.childer[word.charAt(i) - 'a'] = new TrieNode(word.charAt(i));
            }
            p = p.childer[word.charAt(i) - 'a'];
        }*/
        for (char c : word.toCharArray()) {         //简写
            if (p.childer[c - 'a'] == null) p.childer[c - 'a'] = new TrieNode(c);
            p = p.childer[c - 'a'];
        }
        p.isEng = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {     //搜索全部,即最后节点为Nil
        TrieNode p = root;
        for (char c : word.toCharArray()) {
            if (p.childer[c - 'a'] == null) return false;
            p = p.childer[c - 'a'];
        }
        /*for (int i = 0; i < word.length(); i++) {
            if (p.childer[word.charAt(i) - 'a'] == null) return false;
            p = p.childer[word.charAt(i) - 'a'];
        }*/
        return p.isEng;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {        //只要匹配即可以
        TrieNode p = root;
        for (char c : prefix.toCharArray()) {
            if (p.childer[c - 'a'] == null) return false;
            p = p.childer[c - 'a'];
        }
        return true;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 字典树
  • 类似的应用场景
  • 字典树的实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档