Node
- 每個Node用HashMap來實現, key是char, value是一個內部類Data
- Data有兩個成員, next指向下一個Node; isWord表示這個字母是不是單詞的結尾
- 內部類的成員和方法即使是private, 外部類也可訪問
- Node有put方法, 用來放入對應的字母, 如果這個字母已經在node裏了, 就看看需不需要改isWord
- Node有getNext方法, 根據字母返回下一個Node
如何插入?
- 遍歷字符串, 對於每一個字符, 往node裏面put一次, 然後node往下走,
- 如果遇到了結尾, 還要把isWord設爲true
關於內部類的知識
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);
}
}