package tree;import java.util.TreeMap;publicclassTrie{privateclassNode{publicboolean isWord;public TreeMap<Character, Node> next;publicNode(boolean isWord){this.isWord = isWord;
next =newTreeMap<>();}publicNode(){this(false);}}private Node root;privateint size;publicTrie(){
root =newNode();
size =0;}publicintgetSize(){return size;}publicvoidadd(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,newNode());}
cur = cur.next.get(c);}if(!cur.isWord){
cur.isWord =true;
size++;}}publicbooleancontains(String word){
Node cur = root;for(int i =0; i < word.length(); i++){char c = word.charAt(i);if(cur.next.get(c)== null){returnfalse;}
cur = cur.next.get(c);}return cur.isWord;}}
1.4 Trie 前缀搜索
// 查询是否在 Trie 中有单词以 prefix 为前缀publicbooleanisPrefix(String prefix){
Node cur = root;for(int i =0; i < prefix.length(); i++){char c = prefix.charAt(i);if(cur.next.get(c)== null){returnfalse;}
cur = cur.next.get(c);}returntrue;}