Easy understand Java Solution


  • 0

    I have nothing to say ...

    public class WordDictionary {
        
        public class TrieNode{
            public TrieNode[] next;
            public boolean isWord;
            
            public TrieNode(){
                next = new TrieNode[26];
            }
        }
    
        TrieNode root = new TrieNode();
    
        // Adds a word into the data structure.
        public void addWord(String word) {
            TrieNode p = root;
            for(char c: word.toCharArray()){
                int i = c-'a';
                if(p.next[i]==null) p.next[i]=new TrieNode();
                p=p.next[i];
            }
            p.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.toCharArray(), 0, root);
        }
        
        public boolean search(char[] arr, int pos, TrieNode p){
            if(pos==arr.length)
                return p.isWord;
                
            char c=arr[pos];
            if(c!='.'){
                int i=c-'a';
                return p.next[i]!=null && search(arr, pos+1, p.next[i]);
            }else{
                for(int i=0;i<26;++i){
                    if(p.next[i]!=null && search(arr, pos+1, p.next[i])){
                        return true;
                    }
                }
                return false;
            }
        }
    }
    
    

Log in to reply
 

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