• 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);
     */
    
  • 相关阅读:
    C# 日期格式化
    MVVM框架下,WPF实现Datagrid里的全选和选择
    【转】WPF 给DataGridTextColumn统一加上ToolTip
    C# 获取当前月第一天和最后一天 计算两个日期差多少天
    WPF 弹出UserControl
    斐讯Fir302b救砖教程
    mvc 传递匿名对象
    Java HttpGet
    Java xml object 互转
    HttpClientHandler
  • 原文地址:https://www.cnblogs.com/yuchenkit/p/7223486.html
Copyright © 2020-2023  润新知