二刷208. Implement Trie (Prefix Tree)

huahua讲得太好了, 感觉今天才懂trie到底是个啥。
https://www.youtube.com/watch?v=8d_HdK0f2B4
关键点

  • root是空的,可以类比链表里的dummy node
  • 每个node的children都被初始化为一个TrieNode[26], 依次用来储存a, b, c, d, 一开始我一直不明白我到了这个node怎么知道这个地方的word到底是什么,但实际上因为这个顺序的关系,你到的是哪一个index的位置,自然就知道单词了。比如1 - 2 - 3肯定对应的就是 bcd这个单词,所以不需要另外写方法去记录。
  • insert和find写得其实很类似,都是先用p = root, 然后一个字符一个字符地traverse, 看对应的index是否为null. insert的时候如果遇到null就new,然后不再null,继续traverse.如果是find遇到null说明这个词不存在!
class Trie {
    class TrieNode{
        TrieNode[] children;
        boolean isWord;
        public TrieNode(){
            this.children = new TrieNode[26];
            this.isWord = false;
        }
    }
    TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        this.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++){
            int index = word.charAt(i) - 'a';
            if (p.children[index] == null){
                p.children[index] = new TrieNode();
            }
            p = p.children[index];
        }
        p.isWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        return find(word) != null && find(word).isWord; 
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        return find(prefix) != null;    
    }
    
    private TrieNode find(String s){
        TrieNode p = root;
        for (int i = 0; i < s.length(); i++){
            int index = s.charAt(i) - 'a';
            p = p.children[index];
            if (p == null){
                break;
            }
        }
        return p;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,350评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,932评论 18 399
  • 上课第一天,有点兴奋,仿佛重回学生时代。 阿炳老师并没有想象中用xcode,而是用终端敲代码。 有点意思
    牛牛很牛阅读 1,040评论 0 0
  • 有人说过,父母这一生给你最大的礼物就是你的生命。 有一天,我发烧了。妈妈看我有点不和往常一样,就习惯性的摸了摸我的...
    語丬會初鈿阅读 1,716评论 0 2
  • 昨日端午节,也是老妈的六十四岁生日,我们姐妹四个相约都回到了农村的娘家为老妈祝寿。 正当我们姐几个洗菜切菜忙得不亦...
    吾辈阅读 1,664评论 0 0