zoukankan      html  css  js  c++  java
  • 实现前缀树

     class Trie {
    
            //是否是结尾节点
            boolean isEnd = false;
            //a-z的实现,如果是汉字需要用HashMap保存
            Trie[] children = new Trie[26];
            
            /**
             * 插入
             */
            public void insert(String word) {
                Trie[] cur = this.children;
                for (int i = 0; i < word.length(); i++) {
                    int idx = word.charAt(i) - 97;
                    Trie tmp;
                    if (cur[idx] == null) {
                        tmp = new Trie();
                        cur[idx] = tmp;
                    } else {
                        tmp = cur[idx];
                    }
                    if (i == word.length() - 1) tmp.isEnd = true;
                    cur = tmp.children;
                }
            }
    
            /**
             * 查找某个单词是否存在
             */
            public boolean search(String word) {
                Trie[] cur = this.children;
                for (int i = 0; i < word.length(); i++) {
                    int idx = word.charAt(i) - 97;
                    if (cur[idx] == null) return false;
                    //和startwith区别就在这,必须是单词结尾节点才算找到
                    if (i == word.length() - 1 && !cur[idx].isEnd) return false;
                    cur = cur[idx].children;
                }
                return true;
            }
    
            public boolean startsWith(String prefix) {
                Trie[] cur = this.children;
                for (int i = 0; i < prefix.length(); i++) {
                    int idx = prefix.charAt(i) - 97;
                    if (cur[idx] == null) return false;
                    cur = cur[idx].children;
                }
                return true;
            }
        }
    
  • 相关阅读:
    go语言学习笔记四(函数、包和错误处理)
    objection内存漫游实战
    脱壳工具FRIDA-DEXDump
    jsdom 用法技巧
    关于adb安装指定版本
    ob混淆
    js原型链hook
    js逆向核心:扣代码2
    ssl_logger捕获得物app双向验证数据
    js逆向核心:扣代码
  • 原文地址:https://www.cnblogs.com/CodeSpike/p/13667001.html
Copyright © 2011-2022 走看看