C++实现LeetCode(676.实现神奇字典)

 更新时间:2021年08月09日 15:20:37   作者:Grandyang  
这篇文章主要介绍了C++实现LeetCode(676.实现神奇字典),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[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 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:

  1. You may assume that all the inputs are consist of lowercase letters a-z.
  2. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
  3. 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.

这道题让我们设计一种神奇字典的数据结构,里面有一些单词,实现的功能是当我们搜索一个单词,只有存在和这个单词只有一个位置上的字符不相同的才能返回true,否则就返回false,注意完全相同也是返回false,必须要有一个字符不同。博主首先想到了One Edit Distance那道题,只不过这道题的两个单词之间长度必须相等。所以只需检测和要搜索单词长度一样的单词即可,所以我们用的数据结构就是根据单词的长度来分,把长度相同相同的单词放到一起,这样就可以减少搜索量。那么对于和要搜索单词进行比较的单词,由于已经保证了长度相等,我们直接进行逐个字符比较即可,用cnt表示不同字符的个数,初始化为0。如果当前遍历到的字符相等,则continue;如果当前遍历到的字符不相同,并且此时cnt已经为1了,则break,否则cnt就自增1。退出循环后,我们检测是否所有字符都比较完了且cnt为1,是的话则返回true,否则就是跟下一个词比较。如果所有词都比较完了,则返回false,参见代码如下:

解法一:

class MagicDictionary {
public:
    /** Initialize your data structure here. */
    MagicDictionary() {}
    
    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for (string word : dict) {
            m[word.size()].push_back(word);
        }
    }
    
    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    bool search(string word) {
        for (string str : m[word.size()]) {
            int cnt = 0, i = 0;
            for (; i < word.size(); ++i) {
                if (word[i] == str[i]) continue;
                if (word[i] != str[i] && cnt == 1) break; 
                ++cnt;
            }
            if (i == word.size() && cnt == 1) return true;
        }
        return false;
    }

private:
    unordered_map<int, vector<string>> m;
};

下面这种解法实际上是用到了前缀树中的search的思路,但是我们又没有整个用到prefix tree,博主感觉那样写法略复杂,其实我们只需要借鉴一下search方法就行了。我们首先将所有的单词都放到一个集合中,然后在search函数中,我们遍历要搜索的单词的每个字符,然后把每个字符都用a-z中的字符替换一下,形成一个新词,当然遇到本身要跳过。然后在集合中看是否存在,存在的话就返回true。记得换完一圈字符后要换回去,不然就不满足只改变一个字符的条件了,参见代码如下:

解法二:

class MagicDictionary {
public:
    /** Initialize your data structure here. */
    MagicDictionary() {}
    
    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for (string word : dict) s.insert(word);
    }
    
    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    bool search(string word) {
        for (int i = 0; i < word.size(); ++i) {
            char t = word[i];
            for (char c = 'a'; c <= 'z'; ++c) {
                if (c == t) continue;
                word[i] = c;
                if (s.count(word)) return true;
            }
            word[i] = t;
        }
        return false;
    }
    
private:
    unordered_set<string> s;
};

类似题目:

Implement Trie (Prefix Tree)

参考资料:

https://discuss.leetcode.com/topic/103004/c-clean-code

https://discuss.leetcode.com/topic/102992/easy-14-lines-java-solution-hashmap

到此这篇关于C++实现LeetCode(676.实现神奇字典)的文章就介绍到这了,更多相关C++实现实现神奇字典内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • cocos2dx实现橡皮擦效果以及判断是否擦除完毕

    cocos2dx实现橡皮擦效果以及判断是否擦除完毕

    这篇文章主要为大家详细介绍了cocos2dx实现橡皮擦效果以及判断是否擦除完毕,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • C++ 打开选择文件夹对话框选择目录的操作

    C++ 打开选择文件夹对话框选择目录的操作

    这篇文章主要介绍了C++ 打开选择文件夹对话框选择目录的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • C语言数据结构之算法的时间复杂度

    C语言数据结构之算法的时间复杂度

    这篇文章主要介绍了C语言数据结构之算法的时间复杂度,文章基于c语言的相关资料展开详细介绍,具有一定的参价值,需要的小伙伴可以参考一下
    2022-05-05
  • C/C++编程中const的使用详解

    C/C++编程中const的使用详解

    这篇文章主要为大家详细介绍了C/C++编程中const的使用,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • 详解Matlab中自带的Java操作合集

    详解Matlab中自带的Java操作合集

    其实Matlab中也有一些自带的Java操作,例如:获取鼠标在全屏位置、获取当前剪切板内容、获取鼠标处像素颜色等,本文总结了七个这样的操作,感兴趣的可以了解一下
    2022-03-03
  • C语言+EasyX实现数字雨效果

    C语言+EasyX实现数字雨效果

    这篇文章主要为大家详细介绍了C语言+EasyX实现数字雨效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-11-11
  • C++新特性详细分析基于范围的for循环

    C++新特性详细分析基于范围的for循环

    C++11这次的更新带来了令很多C++程序员期待已久的for range循环,每次看到javascript, lua里的for range,心想要是C++能有多好,心里别提多酸了。这次C++11不负众望,再也不用羡慕别家人的for range了。下面看下C++11的for循环的新用法
    2022-04-04
  • c++中的前向声明用法解读

    c++中的前向声明用法解读

    这篇文章主要介绍了c++中的前向声明用法解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • c语言实现php的trim标签

    c语言实现php的trim标签

    本文给大家介绍的是使用C语言实现php的trim标签功能的代码,非常的实用,其主要作用是清除字符串开头结尾除空白,有需要的小伙伴可以参考下。
    2016-01-01
  • C++中的数组、链表与哈希表

    C++中的数组、链表与哈希表

    这篇文章主要介绍了C++中的数组、链表与哈希表,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09

最新评论