Simple Java solution using two sets for quick optimization


  • 0
    G
        Set<String> set;
        Set<Integer> lset;
        /** Initialize your data structure here. */
        public MagicDictionary() {
            set = new HashSet<String>();
            lset = new HashSet<Integer>();
        }
        
        /** Build a dictionary through a list of words */
        public void buildDict(String[] dict) {
            
            for(String word : dict){
                set.add(word);
                lset.add(word.length());
            }
        }
        
        /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
        public boolean search(String word) {
            
            if(!lset.contains(word.length()))
                return false;
            char[] wordarr = word.toCharArray();
            for(int i=0;i<wordarr.length;i++){
            
                char c =wordarr[i];
                
                for(char t='a';t<='z';t++){
                    
                    if(t==c)
                        continue;
                    
                    wordarr[i]=t;
                    String nstr = new String(wordarr);
                    if(set.contains(nstr))
                        return true;
                    
                    }
                
                wordarr[i]=c;
     
            }
            
            return false;
            
        }
    

Log in to reply
 

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