• [leedcode 208] Implement Trie (Prefix Tree)


    Trie树又被称为字典树、前缀树,是一种用于快速检索的多叉树。Tried树可以利用字符串的公共前缀来节省存储空间。

    但如果系统存在大量没有公共前缀的字符串,相应的Trie树将非常消耗内存。(下图为Wiki上的Trie树示意图, https://en.wikipedia.org/wiki/Trie)

    1. 子节点用hashMap表示
    2. isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀。

    Implement a trie with insertsearch, and startsWith methods.

    class TrieNode {
        // Initialize your data structure here.
            boolean isWord;
            public HashMap<Character,TrieNode> nexts;
            public TrieNode(){
                nexts=new HashMap<Character,TrieNode>();
            }
        
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            int start=0;
            int end=word.length();
            TrieNode p=root;
            while(start<end){
               TrieNode node= p.nexts.get(word.charAt(start));
               if(node!=null){
                   p=node;
                   start++;
               }else break;
            }
            while(start<end){
                TrieNode trie=new TrieNode();
                p.nexts.put(word.charAt(start),trie);
                p=trie;
                start++;
            }
            p.isWord=true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode p=root;
            for(int i=0;i<word.length();i++){
               TrieNode child= p.nexts.get(word.charAt(i));
               if(child==null){
                   return false;
               }
               p=child;
            }
            return p.isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode p=root;
            for(int i=0;i<prefix.length();i++){
                TrieNode child=p.nexts.get(prefix.charAt(i));
                if(child==null) return false;
                p=child;
            }
            return true;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");
  • 相关阅读:
    Many Operations(位运算、递推)
    Link with Monotonic Subsequence(构造)
    Yet Another RGB Sequence(排列组合)
    区块反转(模拟、链表)
    每周一坑微信测试号登录失败redirect10003
    每周一坑上线前一天【下】
    局域网内传输工具snapdrop
    每周闲谈上线前系统检查
    每周一坑管理端和手机端版本号不一致
    电源被关后的ESXI服务器恢复
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4703334.html
Copyright © 2020-2023  润新知