My Java Solution Using HashMap


  • 0
    G
    class TrieNode {
        Map<Character,TrieNode> hm;
        boolean isEnd;
        // Initialize your data structure here.
        public TrieNode() {
            hm = new HashMap<Character,TrieNode>();
            isEnd = false;
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode iter = root;
            for(char c : word.toCharArray()){
                if(!iter.hm.containsKey(c)){
                    iter.hm.put(c,new TrieNode());
                }
                iter = iter.hm.get(c);
            }
            iter.isEnd = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode iter = root;
            for(char c : word.toCharArray()){
                if(!iter.hm.containsKey(c)){
                    return false;
                }
                iter = iter.hm.get(c);
            }
            return iter.isEnd;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode iter = root;
            for(char c : prefix.toCharArray()){
                if(!iter.hm.containsKey(c)){
                    return false;
                }
                iter = iter.hm.get(c);
            }
            return true;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.