• [LeetCode]208. 实现 Trie (前缀树)


    题目

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

    示例:

    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
    说明:

    你可以假设所有的输入都是由小写字母 a-z 构成的。
    保证所有输入均为非空字符串。

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

    题解

    Trie树:字典树、前缀树。重点在于理解Trie树的结构。
    字母可以看做对应树的边。
    区别TrieNode和Trie的构造函数。

    代码

    class TrieNode{
        TrieNode[] child;
        boolean endFlag;    
        
        public TrieNode(){
            child=new TrieNode[26];
            endFlag=false;
        }
    }
    
    class Trie {
        TrieNode root;
        
        /** Initialize your data structure here. */
        public Trie() {
            root=new TrieNode();
        }
        
        /** Inserts a word into the trie. */
        public void insert(String word) {
            TrieNode curNode=root;
            for(int i=0;i<word.length();++i){
                char c=word.charAt(i);
                if(curNode.child[c-'a']==null){
                    curNode.child[c-'a']=new TrieNode();
                }
                curNode=curNode.child[c-'a'];
            }
            curNode.endFlag=true;
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            TrieNode curNode=root;
            for(int i=0;i<word.length();++i){
                char c=word.charAt(i);
                if(curNode.child[c-'a']==null){
                    return false;
                }
                curNode=curNode.child[c-'a'];
            }
            return curNode.endFlag==true?true:false;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            TrieNode curNode=root;
            for(int i=0;i<prefix.length();++i){
                char c=prefix.charAt(i);
                if(curNode.child[c-'a']==null){
                    return false;
                }
                curNode=curNode.child[c-'a'];
            }
            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);
     */
    
  • 相关阅读:
    《大话数据结构》最小生成树——Prim算法
    《大话数据结构》图的BFS和DFS
    寒假集训日志(三)——数论
    寒假集训日志(二)——最小生成树,拓扑排序,欧拉回路,连通路
    set
    寒假集训日志(一)——图,最短路问题
    经典的图论算法,C++描述
    动态数组
    stack and queue
    最长递增子序列,最长公共子串,最长公共子序列问题,最长公共增长子序列问题
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/11332919.html
Copyright © 2020-2023  润新知