zoukankan      html  css  js  c++  java
  • 208. Implement Trie (Prefix Tree)

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

    Note:
    You may assume that all inputs are consist of lowercase letters a-z.


    这棵Trie树里存的都是英文小写字母,因此每个Node有26个孩子,代表它的下一个字符a-z。同时,每个节点中,用count记录到这个节点是否是一个endpoint
    ** 这里没有对Trie树做删除的操作。在查找prefix时,我是判断如果对prefix里的字符一个个遍历,如果节点都不为空,表示存在以Prefix为前缀的字符串。*如果加上删除操作,要确保把Trie里的整条路径删除。
    思考:Trie Tree的优缺点有什么?
    public class Trie {
        Trie[] children;
        int count = 0;
        /** Initialize your data structure here. */
        public Trie() {
            children = new Trie[26];
        }
        
        /** Inserts a word into the trie. */
        public void insert(String word) {
            if (word.equals("")) {
                count++;
            }
            Trie cur = this;
            int i = 0;
            while (i < word.length()) {
                if (cur.children[word.charAt(i) - 'a'] == null) {
                    cur.children[word.charAt(i) - 'a'] = new Trie();
                }
                cur = cur.children[word.charAt(i) - 'a'];
                i++;
            }
            cur.count++;
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            Trie cur = this;
            int i = 0;
            while (cur != null && i < word.length()) {
                cur = cur.children[word.charAt(i) - 'a'];
                i++;
            }
            if (cur == null || cur.count == 0) {
                return false;
            }
            return true;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            Trie cur = this;
            int i = 0;
            while (cur != null && i < prefix.length()) {
                cur = cur.children[prefix.charAt(i) - 'a'];
                i++;
            }
            if (cur == null) {
                return false;
            }
            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);
     */
    
  • 相关阅读:
    第5章 构建Spring Web应用程序
    第4章 面向切面的Spring
    第3章 高级装配
    js json和字符串的互转
    webservice CXF入门服务端
    javascript的解析执行顺序
    java AES加密解密
    redis学习 java redis应用
    项目部署操作linux数据库mysql出现表找不到
    灯具板SOP
  • 原文地址:https://www.cnblogs.com/yuchenkit/p/7223486.html
Copyright © 2011-2022 走看看