zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    Spring学习8- SSH需要的jar包
    Spring学习8-SSH+Log4j黄金整合
    Spring学习8-Spring事务管理(注解式声明事务管理)
    dbvisualizer客户端执行创建存储过程或自定义函数语句的方法
    jvm的组成入门
    java的反射机制
    oracle排序子句的特殊写法与ORA-01785错误
    javascript的数据类型检测
    jsp的el表达式
    javascript模块化编程的cmd规范(sea.js)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13445877.html
Copyright © 2011-2022 走看看