My clean solution in Java


  • 0
    T

    Interestingly, this code wasn't accepted on first try (time limit exceeded), but second submission of the same code was.

    class TrieNode {
        // Initialize your data structure here.
        
        private Map<Character, TrieNode> map = new HashMap<>();
        private boolean isWord;
        
        public TrieNode() {
            
        }
        
        public TrieNode next(char c) {
            TrieNode next = map.get(c);
            if (next == null) {
                next = new TrieNode();
                map.put(c, next);
            }
            return next;
        }
        
        public boolean hasNext(char c) {
            return map.containsKey(c);
        }
        
        public void markMyWord() {
            isWord = true;
        }
        
        public boolean isWord() {
            return isWord;
        }
     }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode node = wordNode(word, true);
            node.markMyWord();
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode node = wordNode(word, false);
            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 = wordNode(prefix, false);
            return node != null;
        }
    
        private TrieNode wordNode(String word, boolean create) {
            if (word == null) {
                throw new IllegalArgumentException();
            }
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (!create && !node.hasNext(c)) {
                    return null;
                }
                node = node.next(c);
            }
            return node;
        }
    
    }

Log in to reply
 

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