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;
            }
        }
    
  • 相关阅读:
    Web服务技术协议:REST与SOAP
    几种常见的Web服务器
    在浏览器中输入网址后是怎么跳转到指定的服务器的
    forward(请求转发)和redirect(重定向)的区别
    Hook钩子编程
    闭包
    JSP
    临界区与锁
    进程
    LeetCode Search for a Range
  • 原文地址:https://www.cnblogs.com/CodeSpike/p/13667001.html
Copyright © 2011-2022 走看看