zoukankan      html  css  js  c++  java
  • 10-4 字典树的前缀查询

    前缀查询:查询字典树中是否存在以指定字符串为前缀的单词!

    mport java.util.TreeMap;
    
    public class Trie {
    
        private class Node{
    
            public boolean isWord;
            public TreeMap<Character, Node> next;
    
            public Node(boolean isWord){
                this.isWord = isWord;
                next = new TreeMap<>();
            }
    
            public Node(){
                this(false);
            }
        }
    
        private Node root;
        private int size;
    
        public Trie(){
            root = new Node();
            size = 0;
        }
    
        // 获得Trie中存储的单词数量
        public int getSize(){
            return size;
        }
    
        // 向Trie中添加一个新的单词word
        public void add(String word){
    
            Node cur = root;
            for(int i = 0 ; i < word.length() ; i ++){
                char c = word.charAt(i);
                if(cur.next.get(c) == null)
                    cur.next.put(c, new Node());
                cur = cur.next.get(c);
            }
    
            if(!cur.isWord){
                cur.isWord = true;
                size ++;
            }
        }
    
        // 查询单词word是否在Trie中
        public boolean contains(String word){
    
            Node cur = root;
            for(int i = 0 ; i < word.length() ; i ++){
                char c = word.charAt(i);
                if(cur.next.get(c) == null)
                    return false;
                cur = cur.next.get(c);
            }
            return cur.isWord;
        }
    
        // 查询是否在Trie中有单词以prefix为前缀
        // 前缀:一个单词的前若干个字母组成的串称为这个单词的一个前缀,整合单词也是这个单词本身的一个前缀
        // 前缀查询和contains查询逻辑相似
        public boolean isPrefix(String prefix){
    
            Node cur = root;
            for(int i = 0 ; i < prefix.length() ; i ++){
                char c = prefix.charAt(i);
                if(cur.next.get(c) == null)
                    return false;
                cur = cur.next.get(c);
            }
    
            return true;
        }
    }
    

      

  • 相关阅读:
    739. Daily Temperatures
    556. Next Greater Element III
    1078. Occurrences After Bigram
    1053. Previous Permutation With One Swap
    565. Array Nesting
    1052. Grumpy Bookstore Owner
    1051. Height Checker
    数据库入门及SQL基本语法
    ISCSI的概念
    配置一个IP SAN 存储服务器
  • 原文地址:https://www.cnblogs.com/lpzh/p/12552105.html
Copyright © 2011-2022 走看看