字典树(Trie树) Java实现源码参考

定义

字典树,又称为单词查找树,Tire数,是一种树形结构,它是一种哈希树的变种。用于保存大量的字符串。它的优点是:利用字符串的公共前缀来节约存储空间。
字典树(Trie树) Java实现源码参考_第1张图片

字典树结构对应的Java源码

public class Trie {
    char val;

    boolean isEnd = false;

    Trie[] subChildren = new Trie[26];

    public Trie(char val) {
        this.val = val;
    }
}

字典树增删改查对应的Java源码

本次示例仅展示了insert,find方法

public class TrieDemo {

    Trie root = new Trie(' ');

    public void insert(String word) {

        Trie node = root;
        for (int i = 0; i < word.length(); i++) {

            char c = word.charAt(i);
            int idx = c - 65;

            if (node.subChildren[idx] == null) {
                Trie sub = new Trie(c);
                node.subChildren[idx] = sub;
            }
            node = node.subChildren[idx];
        }
        node.isEnd = true;

    }

    public boolean exist(String word) {

        Trie node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            int idx = c - 65;

            if (node.subChildren[idx] == null) {
                return false;
            }
            node=node.subChildren[idx];
        }

        return node.isEnd;
    }


    public static void main(String[] args) {
        TrieDemo demo = new TrieDemo();
        demo.insert("HELLO");
        System.out.println(demo.root);
        boolean f = demo.exist("HELLO");
        System.out.println(f);
    }
}

字典树增删改查线程安全版本对应的Java源码

public class TrieSynchronizedDemo {

    Trie root = new Trie(' ');

    public void insert(String word) {

        Trie node = root;
        for (int i = 0; i < word.length(); i++) {

            char c = word.charAt(i);
            int idx = c - 65;

            if (node.subChildren[idx] == null) {
                synchronized (node) {
                    if (node.subChildren[idx] == null) {
                        Trie sub = new Trie(c);
                        node.subChildren[idx] = sub;
                    }
                }

            }
            node = node.subChildren[idx];
        }
        node.isEnd = true;

    }

    public boolean exist(String word) {

        Trie node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            int idx = c - 65;

            if (node.subChildren[idx] == null) {
                return false;
            }
            node = node.subChildren[idx];
        }

        return node.isEnd;
    }


    public static void main(String[] args) {
        TrieSynchronizedDemo demo = new TrieSynchronizedDemo();
        demo.insert("HELLO");
        System.out.println(demo.root);
        boolean f = demo.exist("HELLO");
        System.out.println(f);
    }

}

参考文章:
https://www.cnblogs.com/xujian2014/p/5614724.html

你可能感兴趣的:(java,java,算法)