Java HashSet Iterator Solution. 96ms


  • 0
    J
    class MagicDictionary {
        private Set<String> set;
    
        /** Initialize your data structure here. */
        public MagicDictionary() {
            set = new HashSet<>();
        }
        
        /** Build a dictionary through a list of words */
        public void buildDict(String[] dict) {
            for(String word : dict) {
                set.add(word);
            }
        }
        
        /** 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) {
            Iterator<String> it = set.iterator();
            while(it.hasNext()) {
                String s = it.next();
                if(s.length() == word.length()) {
                    if(checkWord(s, word) == true) {
                        return true;
                    }
                }
                
            }
            return false;
        }
        
        private boolean checkWord(String s, String w) {
            if(s.equals(w)) {
                return false;
            }
            for(int i = 0; i < s.length(); i++) {
                if(s.charAt(i) != w.charAt(i)) {
                    return s.substring(i+1).equals(w.substring(i+1));
                }
            }
            return true;
        }
    }
    
    /**
     * Your MagicDictionary object will be instantiated and called as such:
     * MagicDictionary obj = new MagicDictionary();
     * obj.buildDict(dict);
     * boolean param_2 = obj.search(word);
     */
    

Log in to reply
 

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