当前位置 博文首页 > 文章内容

    0208. Implement Trie (Prefix Tree) (M)

    作者: 栏目:未分类 时间:2020-08-06 14:01:15

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    Implement Trie (Prefix Tree) (M)

    题目

    Implement a trie with insert, search, and startsWith methods.

    Example:

    Trie trie = new Trie();
    
    trie.insert("apple");
    trie.search("apple");   // returns true
    trie.search("app");     // returns false
    trie.startsWith("app"); // returns true
    trie.insert("app");   
    trie.search("app");     // returns true
    

    Note:

    • You may assume that all inputs are consist of lowercase letters a-z.
    • All inputs are guaranteed to be non-empty strings.

    题意

    实现字典树。

    思路

    每个结点最多可以有26个子结点,同时给每个结点设置一个标志位用来指明当前结点是否为一个单词的结尾。


    代码实现

    Java

    class Trie {
        private Node root;
    
        /** Initialize your data structure here. */
        public Trie() {
            root = new Node();
        }
    
        /** Inserts a word into the trie. */
        public void insert(String word) {
            Node p = root;
            for (char c : word.toCharArray()) {
                if (p.children[c - 'a'] == null) {
                    p.children[c - 'a'] = new Node();
                }
                p = p.children[c - 'a'];
            }
            p.end = true;
        }
    
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            Node p = prefix(word);
            return p != null && p.end;
        }
    
        /**
         * Returns if there is any word in the trie that starts with the given prefix.
         */
        public boolean startsWith(String prefix) {
            return prefix(prefix) != null;
        }
    
        private Node prefix(String word) {
            Node p = root;
            for (char c : word.toCharArray()) {
                if (p.children[c - 'a'] == null) {
                    return null;
                }
                p = p.children[c - 'a'];
            }
            return p;
        }
    }
    
    class Node {
        Node[] children = new Node[26];
        boolean end;
    }