• (medium)LeetCode .Implement Trie (Prefix Tree)


    Implement a trie with insertsearch, and startsWith methods.

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

    思路:实现单词查找树,它是一种树形结构;用于保存大量的字符串。它的优点是:利用字符串的公共前缀来节约存储空间。每个节点有26个从节点。isEndOfWord,children,两个关键变量。

    代码如下:

    class TrieNode {
        // Initialize your data structure here.
        boolean isEndOfWord;
        TrieNode[] children;
        public TrieNode() {
            this.isEndOfWord=false;
            this.children=new TrieNode[26];
        }
        
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode runner=root;
            for(char c:word.toCharArray()){
                if(runner.children[c-'a']==null){
                    runner.children[c-'a']=new TrieNode();
                }
                runner=runner.children[c-'a'];
            }
            runner.isEndOfWord=true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
           TrieNode runner=root;
           for(char c:word.toCharArray()){
               if(runner.children[c-'a']==null){
                   return false;
               }else{
                   runner=runner.children[c-'a'];
               }
           }
           return runner.isEndOfWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode runner=root;
            for(char c:prefix.toCharArray()){
                if(runner.children[c-'a']==null){
                    return false;
                }else{
                    runner=runner.children[c-'a'];
                }
            }
            return true;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");
    

      运行结果:

      

  • 相关阅读:
    攻心之战,以情动之;攻城之战,以财诱之;攻坚之战,以力迫之;攻野之战,以势强之
    2005 经典java问题
    Javadoc的简捷使用 zt
    一些入门的java小程序zt
    连载:住在我隔壁储藏室的大学刚毕业的小夫妻zt
    Oracle中發郵件代碼
    程序员职业规划
    IE與Firefox中Cookie的保存方法
    request與response區別
    Html Menu下拉菜單
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4734613.html
Copyright © 2020-2023  润新知