Simplest HashSet solution beats 97.74%


  • 0
    C
    class MagicDictionary {
        Set<String> set = new HashSet<>();
        /** Initialize your data structure here. */
        public MagicDictionary() {
            
        }
        
        /** Build a dictionary through a list of words */
        public void buildDict(String[] dict) {
            for(String s: dict) set.add(s);
        }
        
        /** 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) {
            char[] chars = word.toCharArray();
            for(int i=0;i<chars.length;i++){
                char c = chars[i];
                for(char j='a';j<='z';j++){
                    if(j != c){
                        chars[i] = j;
                        if(set.contains(String.valueOf(chars)))
                            return true;
                    }
                }
                chars[i] = c;
            }
            return false;
        }
    }
    

Log in to reply
 

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