Trie 前綴樹 字典樹 簡介+實現

簡介

在這裏插入圖片描述
最上面的是根結點, 這棵樹中存的單詞是apple, app, all, bat, 如果IsWord爲True, 就說明從根節點連到這個結點的字母組成的是一個單詞

使用前綴樹查詢的時候時間複雜度只和單詞的長度相關

實現

import java.util.TreeMap;

/**
 * 存儲只包含26個字母的單詞
 */
public class Trie {

    private class Node{
        public boolean isWord;  // 是否是一個單詞
        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();
        size = 0;
    }

    public int getSize(){
        return size;
    }

    /**
     * 向Trie中添加一個新的單詞word
     * @param word
     */
    public void add(String word){
        Node cur = root;
        for(int i=0; i<word.length(); i++){
            char c = word.charAt(i);
            // 當前結點不包含到word[i]的結點
            if(cur.next.get(c) == null){
                cur.next.put(c, new Node());  // 新建一個映射
            }
            cur = cur.next.get(c);
        }
        // 如果之前不是個詞
        if(cur.isWord == false){
            cur.isWord = true;
            size++;
        }
    }

    /**
     * 查詢到單詞是否在Trie中
     * @param word
     * @return
     */
    public boolean contains(String word){
        Node cur = root;
        for(int i=0; i<word.length(); i++){
            char c = word.charAt(i);
            if(cur.next.get(c) == null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 可以用 "." 去匹配任意一個字母
     * @param word
     * @return
     */
    public boolean search(String word){
        return search(root, word, 0);
//        return search(root, word);
    }

    /**
     *
     * @param node
     * @param word
     * @param index 表示從word的索引index開始匹配
     * @return
     */
    private boolean search(Node node, String word, int index) {
        // 已經匹配完
        if(index == word.length())
            return node.isWord;

        char c = word.charAt(index);
        if(c != '.'){
            // 如果已經沒有下個結點了
            if(node.next.get(c) == null)
                return false;
            return search(node.next.get(c), word, index+1);
        }
        else{
            for(Node nextNode: node.next.values())
                if(search(nextNode, word, index+1))
                    return true;
            return false;  // 遍歷完都沒有匹配中的
        }
    }

    /**
     *
     * @param node
     * @param word
     * @return
     */
    private boolean search(Node node, String word) {
        if(word.equals("")){
            if(node.isWord){
                return true;
            }
            else{
                return false;
            }
        }

        if(word.charAt(0) == '.'){
            for(Node nextNode: node.next.values()){
                boolean res = search(nextNode, word.substring(1));
                if(res == true){
                    return true;
                }
            }
        }
        else if(node.next.get(word.charAt(0)) != null){
            return search(node.next.get(word.charAt(0)), word.substring(1));
        }
        return false;
    }

    /**
     * 查詢是否存在Trie中有單詞以prefix爲前綴
     * @param prefix
     * @return
     */
    public boolean isPrefix(String prefix){
        Node cur = root;
        for(int i=0; i<prefix.length(); i++){
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }



    public static void main(String[] args) {
        Trie t = new Trie();
        t.add("bad");
        t.add("pad");
        System.out.println(t.contains("bad"));
        System.out.println(t.isPrefix("ba"));
        System.out.println(t.search("ba."));
        System.out.println(t.search(".ad"));
        System.out.println(t.search(".a."));
        System.out.println(t.search("..."));
        System.out.println(t.search("p.a"));
        System.out.println(t.search("b."));
    }
}

練習

LeetCode 677
思路見註釋
假如 insert(“apple”, 3), insert(“all”, 2)

class MapSum {

    private class Node{
        public int value;  // apple的最後一個Node e的value就是3, 前面Node a, p, p, l的value都是0
        public TreeMap<Character, Node> next;  // 如果Node是a, 那next就是Node p, Node l

        // 構造函數
        public Node(int value){
            this.value = value;
            next = new TreeMap<>();
        }

        // 構造函數
        public Node(){
            this(0);
        }
    }

    private Node root;  // 用上面的例子的話, root的next是Node a

    /** Initialize your data structure here. */
    public MapSum() {
        root = new Node();
    }

    public void insert(String key, int val) {
        Node cur = root;
        for(int i=0; i<key.length(); i++){
            char c = key.charAt(i);
            // 如果不存在這個字母的Node, 創建
            if(cur.next.get(c) == null)
                cur.next.put(c, new Node());
            // 移動
            cur = cur.next.get(c);
        }
        cur.value = val;
    }

    public int sum(String prefix) {
        Node cur = root;
        for(int i=0; i<prefix.length(); i++){
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null)
                return 0;
            cur = cur.next.get(c);
        }
        return sum(cur);
    }

    private int sum(Node node){
        // if(node.next.size() == 0)
        //     return node.value;
        // 這個遞歸結束的語句已包含在下面

        int res = node.value;
        for(Node nextNode: node.next.values()){
            res += sum(nextNode);
        }
        return res;
    }

    public static void main(String[] args) {
        MapSum ms = new MapSum();
        ms.insert("apple", 3);
        ms.insert("app", 8);
        ms.insert("bao", 8);
//        ms.sum("ap");
        System.out.println(ms.sum("ap"));
    }
}

其他

侷限性: 佔用的空間會更多, 可以使用壓縮字典樹來解決, 但維護成本又會上去, 有得必有失
在這裏插入圖片描述
還可以用三分搜索樹
在這裏插入圖片描述在這裏插入圖片描述
上面這棵樹中存了單詞dog

後面三張圖來源 link

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