clean and neat java solution


  • 1
    F
        private class TrieNode {
            boolean isWord;
            TrieNode[] next=new TrieNode[26];
        }
    
        private TrieNode root = new TrieNode();
    
        public void addWord(String word) {
            TrieNode p = root;
            for (char c : word.toCharArray()) {
                int idx = c - 'a';
                if (p.next[idx] == null) {
                    p.next[idx] = new TrieNode();
                }
                p = p.next[idx];
            }
            p.isWord = true;
        }
    
        public boolean search(String word) {
            return search(word, 0, root);
        }
    
        private boolean search(String word, int idx, TrieNode trieNode) {
            if (trieNode == null) {
                return false;
            }
            if (idx == word.length()) {
                return trieNode.isWord;
            }
            char c = word.charAt(idx);
            if (c == '.') {
                for (TrieNode node : trieNode.next) {
                    if (search(word, idx + 1, node)) {
                        return true;
                    }
                }
                return false;
            }
            return search(word, idx + 1, trieNode.next[c - 'a']);
        }

Log in to reply
 

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