Simple clean 96% JAVA code


  • 1
    Z
    class TrieNode {
        public boolean isWord;
        public TrieNode[] children = new TrieNode[26];
        public TrieNode(){}
    }
    
    public class WordDictionary {
        TrieNode root = new TrieNode();
        // Adds a word into the data structure.
        public void addWord(String word) {
            TrieNode cur = root;
            for(char c : word.toCharArray()) {
                if(cur.children[c - 'a'] == null) cur.children[c - 'a'] = new TrieNode();
                cur = cur.children[c - 'a'];
            }
            cur.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, 0, root);
            
        }
        private boolean search(String word, int start, TrieNode cur) {
            for(int i = start; i < word.length(); i++) {
                char c = word.charAt(i);
                if(c == '.') {        // handle .
                    for(TrieNode child : cur.children) {   // try each child
                        if(child != null && search(word, i + 1, child)) return true;
                    }
                    return false;     // cannot find any match before
                }
                else {                // normal case
                    if(cur.children[c - 'a'] == null) return false;
                    cur = cur.children[c - 'a'];
                }
            }
            return cur.isWord;
        }
    }
    

Log in to reply
 

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