Since it required exactly one modification, it is better to use following solution. Other

class MagicDictionary {

    Map<String, List<int[]>> map;
    /** Initialize your data structure here. */
    public MagicDictionary() {
        map = new HashMap<>();
    }
    
    /** Build a dictionary through a list of words */
    public void buildDict(String[] dict) {
        for (String word : dict) {
            for (int i = 0; i < word.length(); i++) {
                String key = word.substring(0, i) + word.substring(i + 1);
                if (!map.containsKey(key)) {
                    map.put(key, new ArrayList<>());
                }
                map.get(key).add(new int[]{i, word.charAt(i)});
            }
        }
    }
    
    /** 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) {
        for (int i = 0; i < word.length(); i++) {
            String changed = word.substring(0, i) + word.substring(i + 1);
            if (map.containsKey(changed)) {
                for (int[] pair : map.get(changed)) {
                    if (pair[0] == i && pair[1] != word.charAt(i)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary obj = new MagicDictionary();
 * obj.buildDict(dict);
 * boolean param_2 = obj.search(word);
 */

 

ise, the Trie solution can work. (At least one modify).

posted on 2017-09-20 14:37  keepshuatishuati  阅读(135)  评论(0编辑  收藏  举报