数据结构----Trie(字典树)

文章目录

1. 概述

  1. 适合于字符串操作。
  2. 时间复杂度为O(w):w为查询单词的长度。
  3. 存储结构为,把字符串拆分为字母存储。
  4. 图示:
    在这里插入图片描述

2. 源码

/**
 * Trie(字典树): 适用于操作字符串.
 */
public class Trie {
    private class Node {
        public boolean isWord;

        // 一个字符下可能有多种next字符.
        public TreeMap<Character, Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;

    // 单词数量
    private int size;

    public Trie() {
        root = new Node();
    }

    /**
     * 获取存储的单词数量.
     *
     * @return : 单词数量.
     */
    public int getSize() {
        return size;
    }

    /**
     * 给Trie树种, 添加一个单词.
     *
     * @param word: 添加的单词.
     */
    public void add(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char character = word.charAt(i);
            // 判断下一个节点是否等于当前字符
            if (cur.next.get(character) == null) {
                cur.next.put(character, new Node());
            }

            // 获取这个字符对应的next node.
            // 顺着word依次前进.
            cur = cur.next.get(character);
        }

        // 保证添加的单词不会重复添加
        if (!cur.isWord) {
            size++;
            cur.isWord = true;
        }
    }

    /**
     * 查询此word是否存在于Trie树中.
     *
     * @param word: 查询的单词.
     * @return : true: 包含; false: 不包含.
     */
    public boolean contains(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char character = word.charAt(i);
            // 若下一个节点中的字符和当前字符不一致, 可以判定, 单词不存在.
            if (cur.next.get(character) == null) {
                return false;
            }

            cur = cur.next.get(character);
        }

        // 不能直接返回true;
        // 因为, 哪怕查询的word中所有的字符都存在Trie中;
        // 但是, 最后一个字符没有标识为结尾. 也不能算是单词存在于Trie中.
        return cur.isWord;
    }

    /**
     * 模式匹配, "."代表任意字符. 查询这个单词是否在Trie中.
     *
     * @param word: 需要判断的单词.
     * @return : true:包含; false: 不包含.
     */
    public boolean searchByParttern(String word) {
        return match(root, word, 0);
    }

    /**
     * 以node为根节点, 查询word的index位置是否在当前节点中.
     */
    private boolean match(Node node, String word, int index) {
            if (index == word.length()) {
            return node.isWord;
        }

        char character = word.charAt(index);
        if (character != '.') {
            if (node.next.get(character) == null) {
                return false;
            }

            return match(node.next.get(character), word, index + 1);
        } else {
            // 遍历当前节点下, 可能存在的任意可能性字符.
            for (Character item : node.next.keySet()) {
                // 只要存在一个匹配完成的, 就成功.
                if (match(node.next.get(item), word, index + 1)) {
                    return true;
                }
            }

            return false;
        }
    }

    /**
     * 查询此prefix是否存在于Trie树中.
     *
     * @param prefix: 查询的单词前缀.
     * @return : true: 包含; false: 不包含.
     */
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char character = prefix.charAt(i);
            // 若下一个节点中的字符和当前字符不一致, 可以判定, 前缀不存在.
            if (cur.next.get(character) == null) {
                return false;
            }

            cur = cur.next.get(character);
        }

        return true;
    }

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();
        int n = 1_000_000;
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            words.add(getRandomString(random.nextInt(26)));
        }

        Trie trie = new Trie();
        for (String word : words) {
            trie.add(word);
        }

        for (String word : words) {
            if (trie.contains(word) == false) {
                throw new IllegalArgumentException("Word isn't exist!");
            }
        }

        System.out.println("Test Trie tree is complete!");
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuffer word = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(26);
            word.append(str.charAt(number));
        }

        return word.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值