七、自己動手實現------------“ 線段樹 Segment Tree ”

參考文章:

https://mp.weixin.qq.com/s/hIU4gbKBNypsFWWVxx6x8Q             線段樹      

https://github.com/liuyubobobo/Play-with-Algorithms  

https://blog.csdn.net/qq_41479464/article/details/88586512           java貪心算法(線段樹)的詳細介紹(強推

https://www.cnblogs.com/TheRoadToTheGold/p/6254255.html#undefined           淺談線段樹


 

       線段樹是一個複雜的數據結構,大家如果不太懂,最好先找個視頻來看看,看懂了, 再去找相關的代碼或者博客去看,不然很容易迷糊的。

 

以下是線段樹的主體實現部分:

import java.util.TreeMap;

/// 使用TreeMap的Trie
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;
    }

    // 獲得Trie中存儲的單詞數量
    public int getSize(){
        return size;
    }

    // 向Trie中添加一個新的單詞word
    public void add(String word){

        Node cur = root;
        for(int i = 0 ; i < word.length() ; i ++){
            char c = word.charAt(i);
            if(cur.next.get(c) == null)
                cur.next.put(c, new Node());
            cur = cur.next.get(c);
        }

        if(!cur.isWord){
            cur.isWord = true;
            size ++;
        }
    }

    // 查詢單詞word是否在Trie中
    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;
    }
}

 

 

 查詢 Trie 中是否有 isPrefix 爲前綴 的單詞

// 查詢是否在Trie中有單詞以prefix爲前綴
    public boolean startsWith(String isPrefix){

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

        return true;
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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