AC Java solution using Map for next


  • 4
    N

    This implementation uses Map for next. No stack or recursion is used.

    class TrieNode {
        // Initialize your data structure here.
        public boolean isWord;
        public Map<Character, TrieNode> next; // HashMap
        public TrieNode() {
            isWord = false;
            next = new HashMap<>();
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode node = root;
            for (Character c : word.toCharArray()) {
                if (!node.next.containsKey(c)) {
                    node.next.put(c, new TrieNode());
                }
                node = node.next.get(c);
            }
            node.isWord = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode node = get(word);
            return node != null && node.isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode node = get(prefix);
            return node != null;
        }
        
        //
        private TrieNode get(String key) {
            TrieNode node = root;
            for (Character c : key.toCharArray()) {
                node = node.next.get(c);
                if (node == null) return null;
            }
            return node;
        }
    }

Log in to reply
 

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