zoukankan      html  css  js  c++  java
  • Trie树

    字典树,即Trie树,又称单词查找树或键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

    //leetcode submit region begin(Prohibit modification and deletion)
    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 cur =root;
            char c;
            for(int i = 0;i<word.length();i++){
                c =word.charAt(i);
                if(cur.get(c)!=null){
                    cur= cur.get(c);
                }else {
                    cur.put(c,new TrieNode());
                    cur= cur.get(c);
                }
            }
            cur.setEnd();
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            TrieNode cur = root;
            char c;
            for(int i=0;i<word.length();i++){
                c = word.charAt(i);
                if(cur.get(c)==null)
                    return false;
                cur=cur.get(c);
            }
             return  cur.isEnd==true?true:false;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            TrieNode cur = root;
            char c;
            for(int i=0;i<prefix.length();i++){
                c = prefix.charAt(i);
                if(cur.get(c)==null)
                    return false;
                cur=cur.get(c);
            }
            return true;
        }
    }
    class TrieNode{
    
        Map <Character, TrieNode> nextTreeNode;
        boolean isEnd;
    
        public TrieNode(){
            nextTreeNode = new HashMap<>();
            isEnd = false;
        }
    
        public boolean containsKey(char c){
            return  nextTreeNode.containsKey(c);
        }
    
        public TrieNode get(char c){
            return  nextTreeNode.get(c);
        }
    
        public void put(char c,TrieNode node){
            nextTreeNode.put(c,node);
        }
    
        public boolean isEnd(){
            return  isEnd;
        }
    
        public void setEnd(){
            isEnd = true;
        }
    }
    呵呵
  • 相关阅读:
    20200726 千锤百炼软工人第二十一天
    20200725 千锤百炼软工人第二十天
    20200724 千锤百炼软工人第十九天
    20200723 千锤百炼软工人第十八天
    20200722 千锤百炼软工人第十七天
    20200721 千锤百炼软工人第十六天
    剑指Offer_#64_求1+2+…+n
    剑指Offer_#63_股票的最大利润
    剑指Offer_#62_圆圈中最后剩下的数字
    剑指Offer_#61_扑克牌中的顺子
  • 原文地址:https://www.cnblogs.com/jiazhiyuan/p/12269959.html
Copyright © 2011-2022 走看看