LeetCode - Implement Magic Dictionary

Implement a magic directory with buildDict, and search methods.

For the method buildDict, you‘ll be given a list of non-repetitive words to build a dictionary.

For the method search, you‘ll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.

Example 1:
Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False
Note:
You may assume that all the inputs are consist of lowercase letters a-z.
For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

只需检测和要搜索单词长度一样的单词即可,所以我们用的数据结构就是根据单词的长度来分,把长度相同相同的单词放到一起,这样就可以减少搜索量。那么对于和要搜索单词进行比较的单词,由于已经保证了长度相等,我们直接进行逐个字符比较即可,用cnt表示不同字符的个数,初始化为0。如果当前遍历到的字符相等,则continue;如果当前遍历到的字符不相同,并且此时cnt已经为1了,则break,否则cnt就自增1。退出循环后,我们检测是否所有字符都比较完了且cnt为1,是的话则返回true,否则就是跟下一个词比较。如果所有词都比较完了,则返回false,参见代码如下:

class MagicDictionary {

    private HashMap<Integer, List<String>> map;

    /** Initialize your data structure here. */
    public MagicDictionary() {
        map = new HashMap<Integer, List<String>>();
    }

    /** Build a dictionary through a list of words */
    public void buildDict(String[] dict) {
        for(String str : dict){
            int len = str.length();
            if(map.containsKey(len)){
                map.get(len).add(str);
            }
            else{
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(len, list);
            }
        }
    }

    /** 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(word == null || word.length() == 0){
            return false;
        }
        int len = word.length();
        if(map.containsKey(len)){
            List<String> list = map.get(len);
            for(String str : list){
                if(hasExactOneDifference (str, word)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean hasExactOneDifference(String str1, String str2){
        int cnt = 0;
        for(int i = 0; i< str1.length(); i++){
            if(str1.charAt(i) != str2.charAt(i)){
                if(cnt == 1){
                    return false;
                }
                else{
                    cnt++;
                }
            }
        }
        if(cnt == 1){
            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);
 */

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/10056542.html

时间: 2024-10-06 16:15:36

LeetCode - Implement Magic Dictionary的相关文章

LC 676. Implement Magic Dictionary

Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one

[LeetCode] 676. Implement Magic Dictionary 实现神奇字典

Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one

LeetCode: Implement strStr() [027]

[题目] Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. [题意] 实现库函数strStr(), 功能是在字符串haystack中找出目标串needle第一次出现的索引位 [思路]字符串的匹配,能够用暴力解法,但不推荐.一般使用KMP算法求解. 简要介绍一下KMP的思想: haystack是

[LeetCode] Implement strStr() [18]

题目 Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 原题链接(点我) 解题思路 字符串匹配这也是个老题了,方法主要有下面4种, 1. 暴利破解法(BF),这个没啥说的,就是一轮一轮的比较,知道遇到相匹配的,这个的时间复杂度为O(n^2). 2. KMP,这应该是字符串匹配领域中最长听说的算

[LeetCode] Implement Rand10() Using Rand7()

题目描述 Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10. Do NOT use system's Math.random(). Example 1: Input: 1Output: [7] Example

[leetcode-676-Implement Magic Dictionary]

Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one

leetcode Implement Trie (Prefix Tree)

题目连接 https://leetcode.com/problems/implement-trie-prefix-tree/ Implement Trie (Prefix Tree) Description Implement a trie with insert, search, and startsWith methods. 字典树.. class TrieNode { public: // Initialize your data structure here. bool vis; Tri

[LeetCode] Implement Queue using Stacks 用栈来实现队列

Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You

leetcode | Implement strStr() | 实现字符串查找函数

Implement strStr() : https://leetcode.com/problems/implement-strstr/ Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 如:haystack = "bcbcda"; needle = "bcd" 则 return 2 解析:字符串查找函数,