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);






    }
}






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