• 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;
        }
    }
    

      

  • 相关阅读:
    客户端二进制演示程序
    mormot2数据库操作
    lazarus CRUD
    lazarus安装unidac
    Helper for System.JSON.TJSONObject
    dremio maestro 服务简单介绍
    dremio 社区flight 格式化扩展说明
    hilla maven 插件原理简单说明
    hilla maven 插件实现简单说明
    dremio 反射加速服务简单说明一
  • 原文地址:https://www.cnblogs.com/lpzh/p/12552105.html
Copyright © 2020-2023  润新知