美文网首页
剑指 Offer II 062. 实现前缀树

剑指 Offer II 062. 实现前缀树

作者: Abeants | 来源:发表于2022-08-31 12:19 被阅读0次

    Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

    请你实现 Trie 类:
    Trie() 初始化前缀树对象。
    void insert(String word) 向前缀树中插入字符串 word 。
    boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
    boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

    示例:
    输入
    inputs = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
    inputs = [[], ["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

    提示:
    1 <= word.length, prefix.length <= 2000
    word 和 prefix 仅由小写英文字母组成
    insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/QC3q1f
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题思路及方法

    自己实现前缀树,每一个节点通过一个长度为26的Trie数组指向下一节点,通过字母序的顺序来记录字符串该节点字符;同时isEnd表示某字符串是否在该节点结束。

    插入操作:用一个Trie指针从根节点开始,每一个节点按序记录字符串的每一个字符,如果该节点的该字符位为空,就新增子节点Trie,并移动指针。遍历到最后一位的时候将该节点的isEnd赋值true。
    查找操作:用一个Trie指针从根节点开始,遍历字符串每一位字符并在节点的children数组寻找指定位是否为空,为空表示不存在该字符,返回false;如果遍历到最后一位字符都不为空,就判断该节点的isEnd是否为true。
    startsWith操作:遍历到最后一位时补不需要判断isEnd是否为空,只需在遍历的过程中判断每一位字符节点是否为空。

    class Trie {
    
        private Trie[] children;
        private boolean isEnd;
    
        /** Initialize your data structure here. */
        public Trie() {
            this.children = new Trie[26];
            this.isEnd = false;
        }
    
        /** Inserts a word into the trie. */
        public void insert(String word) {
            // 前缀树节点指针
            Trie nodePt = this;
            // 遍历字符串构建前缀树
            for (int i = 0; i < word.length(); i++) {
                int idx = word.charAt(i) - 'a';
                if (nodePt.children[idx] == null) {
                    nodePt.children[idx] = new Trie();
                }
                // 移动指针
                nodePt = nodePt.children[idx];
            }
            nodePt.isEnd = true;
        }
    
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            // 前缀树结点指针
            Trie pt = this;
            for (int i = 0; i < word.length(); i++) {
                int idx = word.charAt(i) - 'a';
                if (pt.children[idx] == null) return false;
                // 移动指针
                pt = pt.children[idx];
            }
    
            return pt.isEnd;
        }
    
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            // 前缀树结点指针
            Trie pt = this;
            for (int i = 0; i < prefix.length(); i++) {
                int idx = prefix.charAt(i) - 'a';
                if (pt.children[idx] == null) return false;
                // 移动指针
                pt = pt.children[idx];
            }
    
            return true;
        }
    }
    
    /**
     * 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);
     */
    

    结果如下:

    相关文章

      网友评论

          本文标题:剑指 Offer II 062. 实现前缀树

          本文链接:https://www.haomeiwen.com/subject/xoxsnrtx.html