import java.util.HashMap;
import java.util.Map;
public class StandardTrie {
private static class TrieNode{
private int value;
private Map<Character,TrieNode> next=new HashMap<Character,TrieNode>();
}
private TrieNode root=new TrieNode();
public void put(String key,int value){
TrieNode current=root;
for (int i = 0; i < key.length(); i++) {
char c=key.charAt(i);
TrieNode nextNode=current.next.get(c);
if(nextNode==null){
nextNode=new TrieNode();
current.next.put(c,nextNode);
}
current=nextNode;
}
current.value=value;
}
public int get(String key){
TrieNode current=root;
for (int i = 0; i < key.length(); i++) {
char c=key.charAt(i);
current=current.next.get(c);//向下移动
if(current==null){
return 0;
}
}
return current.value;
}
}
标准Trie树
最新推荐文章于 2024-08-30 18:40:43 发布