Easy To Understand Java AC Beats 95.78%!!!


  • 0
    G
    class TrieNode {
        public char val;
        public boolean isWord;
        public TrieNode[] children = new TrieNode[26];
        public TrieNode() {};
        public TrieNode(char c) {
            TrieNode node = new TrieNode();
            node.val = c;
        }
    }
    
    public class WordDictionary {
        TrieNode trie;
        /** Initialize your data structure here. */
        public WordDictionary() {
            trie = new TrieNode();
        }
        
        /** Adds a word into the data structure. */
        public void addWord(String word) {
            TrieNode node = trie;
            for (int i = 0; i < word.length(); ++i) {
                char c = word.charAt(i);
                if (node.children[c - 'a'] == null) node.children[c - 'a'] = new TrieNode(word.charAt(i));
                node = node.children[c - 'a'];
            }
            node.isWord = true;
        }
        
        /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
        public boolean search(String word) {
            return search(word, trie);
        }
        
        public boolean search(String word, TrieNode node) {
            for (int i = 0; i < word.length(); ++i) {
                char c = word.charAt(i);
                if (c == '.') {
                    for (int j = 0; j < 26; ++j) {
                        if (node.children[j] != null) 
                            if (search(word.substring(i + 1, word.length()), node.children[j])) return true;
                    }
                    return false;
                }
                else {
                    if (node.children[c - 'a'] == null) return false;
                    node = node.children[c - 'a'];
                }
            }
            return node.isWord;
        }
    }

Log in to reply
 

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