Concise Java code


  • 0
    public class WordDictionary {
    
        public class TreeNode{
            public TreeNode[] children = new TreeNode[26];
            public boolean isWord = false;
            public TreeNode(){}
        }
        private TreeNode root = new TreeNode();
        private int maxIndex = -1;
        
        // Adds a word into the data structure.
        public void addWord(String word) {
            maxIndex = Math.max(maxIndex, word.length() - 1);
            TreeNode curr = root;
            for(int i = 0; i < word.length(); i++){
                if(curr.children[word.charAt(i)-'a'] == null)
                    curr.children[word.charAt(i)-'a'] = new TreeNode();
                curr = curr.children[word.charAt(i)-'a'];
                if(i == word.length() - 1)
                    curr.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);
        }
        
        public boolean search(String word, int index, TreeNode parent){
            if(index > maxIndex)
                return false;
            char c = word.charAt(index);
            if(index == word.length() - 1){
                if(c == '.')
                    for(int i = 0; i < 26; i++)
                        if(parent.children[i] != null && parent.children[i].isWord)
                            return true;
                else
                    if(parent.children[c - 'a'] != null && parent.children[c - 'a'].isWord)
                        return true;
            }
            else{
                if(c == '.')
                    for(int i = 0; i < 26; i++)
                        if(parent.children[i] != null && search(word, index + 1, parent.children[i]))
                            return true;
                else
                    if(parent.children[c - 'a'] != null && search(word, index + 1, parent.children[c - 'a']))
                        return true;
            }  
            return false;
        }
    }
    

Log in to reply
 

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