实现前缀树

 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;
        }
    }
posted @ 2020-09-14 15:32  CodeSpike  阅读(154)  评论(0编辑  收藏  举报
Live2D