• 0208. Implement Trie (Prefix Tree) (M)


    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;
    }
    
  • 相关阅读:
    九度OJ 1283 第一个只出现一次的字符
    九度OJ 1514 数值的整数次方【算法】
    九度OJ 1512 用两个栈实现队列 【数据结构】
    九度OJ 1513 二进制中1的个数
    九度OJ 1510 替换空格
    九度OJ 1511 从尾到头打印链表
    dom4J使用笔记
    XML的学习
    jaxp使用笔记
    json-lib使用笔记
  • 原文地址:https://www.cnblogs.com/mapoos/p/13445877.html
Copyright © 2020-2023  润新知