import java.util.Map;
import java.util.TreeMap;
public class Trie {
private int size;
private TrieNode root;
public Trie() {
size = 0;
root = new TrieNode();
}
public void put(String word) {
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (!curr.next.containsKey(c)) {
curr.next.put(c, new TrieNode());
}
curr = curr.next.get(c);
}
//如果不是已经存在的word
if (!curr.isWord) {
curr.isWord = true;
size++;
}
}
public boolean query(String word) {
if (word == null || "".equals(word)) {
return false;
}
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(!curr.next.containsKey(c)){
return false;
}
curr = curr.next.get(c);
}
return curr.isWord;
}
class TrieNode {
boolean isWord;
Map<Character, TrieNode> next;
public TrieNode() {
this(false);
}
public TrieNode(Boolean isWord) {
this.isWord = isWord;
next = new TreeMap<Character, TrieNode>();
}
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.put("word");
trie.put("world");
trie.put("one");
trie.put("own");
trie.put("wow");
System.out.println(trie.query("word"));
System.out.println(trie.query("wod"));
System.out.println(trie.query("d"));
}
}