字典樹(Trie樹) Java實現源碼參考

定義

字典樹,又稱爲單詞查找樹,Tire數,是一種樹形結構,它是一種哈希樹的變種。用於保存大量的字符串。它的優點是:利用字符串的公共前綴來節約存儲空間。
在這裏插入圖片描述

字典樹結構對應的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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章