0
点赞
收藏
分享

微信扫一扫

#676 Implement Magic Dictionary

捡历史的小木板 2022-04-13 阅读 30
java

Description

Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.

Implement the MagicDictionary class:

  • MagicDictionary() Initializes the object.
  • void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.
  • bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.

Examples

Example 1:

Constraints:

思路

我能想到的就是根据word_length建立map,来减少循环次数
但最后发现快速执行的代码就用了很普通的String[] dic,好吧是我多虑了

代码

class MagicDictionary {
    Map<Integer, List<String>> dic;
    
    public MagicDictionary() {
        dic = new HashMap<>();
    }
    
    public void buildDict(String[] dictionary) {
        for(String word: dictionary) {
            List<String> tmp =  dic.getOrDefault(word.length(), new ArrayList<>());
            tmp.add(word);
            dic.put(word.length(), tmp);
        }
    }
    
    public boolean different(String a, String b) {
        int count = 0;
        for (int i = 0; i < a.length(); i++){
            if (a.charAt(i) != b.charAt(i))
                count ++;
        }
        
        return count == 1;
    }
    
    public boolean search(String searchWord) {
        int length = searchWord.length();
        if (!dic.containsKey(length))
            return false;
        
        for (String word: dic.get(length)) {
            if (different(word, searchWord))
                return true;
        }
        return false;
    }
}

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

相关推荐

0 条评论