• 实现前缀树


     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;
            }
        }
    
  • 相关阅读:
    php 导出csv文件
    dns 服务器配置
    ettercap ARP dns 欺骗
    for循环内 执行$ajax(){}
    js 如何生成二维数组
    jquery读取csv文件并用json格式输出
    echo 换行
    cmd命令运行php,php通过cmd运行文件
    Git 常用命令整理
    图像裁剪插件
  • 原文地址:https://www.cnblogs.com/CodeSpike/p/13667001.html
Copyright © 2020-2023  润新知