zoukankan      html  css  js  c++  java
  • 标准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;
        }
    }

  • 相关阅读:
    [LeetCode] 617. Merge Two Binary Trees
    [LeetCode] 738. Monotone Increasing Digits
    289. Game of Life
    305. Number of Islands II
    288. Unique Word Abbreviation
    271. Encode and Decode Strings
    393. UTF-8 Validation
    317. Shortest Distance from All Buildings
    286. Walls and Gates
    296. Best Meeting Point
  • 原文地址:https://www.cnblogs.com/i80386/p/2484804.html
Copyright © 2011-2022 走看看