标准Trie树

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

原文地址:https://www.cnblogs.com/i80386/p/2484804.html