• 实现前缀树


     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语言的运行时支持到底是多线程还是单线程
    丑数
    把数组排成最小数
    连续子数组的最大和
    最小的k个数
    数组中出现次数超过一半的数字
    字符串的排序
    二叉搜索树与双向链表
    复杂链表的赋值
    二叉树中和为某一值的路径
  • 原文地址:https://www.cnblogs.com/CodeSpike/p/13667001.html
Copyright © 2020-2023  润新知