Trie樹 Java實現

Node

  • 每個Node用HashMap來實現, key是char, value是一個內部類Data
    • Data有兩個成員, next指向下一個Node; isWord表示這個字母是不是單詞的結尾
    • 內部類的成員和方法即使是private, 外部類也可訪問
  • Node有put方法, 用來放入對應的字母, 如果這個字母已經在node裏了, 就看看需不需要改isWord
  • Node有getNext方法, 根據字母返回下一個Node

如何插入?

  • 遍歷字符串, 對於每一個字符, 往node裏面put一次, 然後node往下走,
  • 如果遇到了結尾, 還要把isWord設爲true

關於內部類的知識

  • 內部類訪問外部類
    OuterClass.this.
    
  • 外部類訪問內部類
    InnerClass ic = this.new InnerClass();
    // 然後就像普通成員變量一樣
    
import java.util.*;

class Node{
    public HashMap<Character, Data> record = new HashMap<>();

    public Data returnData(){
        return this.new Data();
    }

    public class Data{
        public Node next;
        public boolean isWord;

        Data(){
            this.next = null;
            this.isWord = false;
        }

        Data(Node n, boolean is){
            this.next = n;
            this.isWord = is;
        }

        public void setNext(Node n){
            this.next = n;
        }

        public void setIsWord(boolean is){
            this.isWord = is;
        }
    }

    public void put(char c, boolean isWord){
        if(this.record.containsKey(c)){
            if(isWord==true){
                Data tmp = this.record.get(c);
                tmp.setIsWord(true);
            }

        }else{
            Node new_node = new Node();
            Data tmp = new Data(new_node, isWord);
            this.record.put(c,tmp);
        }
    }

    public Node getNext(char c){
        Data tmp = this.record.get(c);
        return tmp.next;
    }
}


class Trie{
    Node root = new Node();

    public void add(String s){
        Node current = root;
        for(int i=0;i<s.length();++i){
            char c = s.charAt(i);

            boolean isWord = false;
            if(i==s.length()-1) isWord = true;

            current.put(c, isWord);
            current = current.getNext(c);
        }
    }


}





public class Main {

    public static void main(String[] args){

       Trie root = new Trie();
       root.add("ad");

       System.out.println(root.root.record.get('a').next.record.get('d').isWord);






    }
}






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