LeetCode676. 实现一个魔法字典


LeetCode676. 实现一个魔法字典

题目描述

本题目来自LeetCode上的『676. 实现一个魔法字典』

设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

实现 MagicDictionary 类:

  • MagicDictionary() 初始化对象
  • void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
  • bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false
示例1:

输入
[“MagicDictionary”, “buildDict”, “search”, “search”, “search”, “search”]
[[], [[“hello”, “leetcode”]], [“hello”], [“hhllo”], [“hell”], [“leetcoded”]]
输出
[null, null, false, true, false, false]

解释
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict([“hello”, “leetcode”]);
magicDictionary.search(“hello”); // 返回 False
magicDictionary.search(“hhllo”); // 将第二个 ‘h’ 替换为 ‘e’ 可以匹配 “hello” ,所以返回 True
magicDictionary.search(“hell”); // 返回 False
magicDictionary.search(“leetcoded”); // 返回 False

提示
  • 1 <= dictionary.length <= 100
  • 1 <= dictionary[i].length <= 100
  • dictionary[i] 仅由小写英文字母组成
  • dictionary 中的所有字符串 互不相同
  • 1 <= searchWord.length <= 100
  • searchWord 仅由小写英文字母组成
  • buildDict 仅在 search 之前调用一次
  • 最多调用 100search

题解

dictionary 中所有单词存入字典树中,对于每一个待查的单词,使用深搜进行匹配,具体如下:

  • 设置变量 cnt 记录不一样的字符的个数。
  • cnt > 1 时,表示至少有两个字符不一样,终止搜索。
  • 遍历当前结点的每一个子结点,在子结点存在的前提下,字符相同,则 cnt 不变,搜索下一个字符;字符不同,cnt + 1 ,搜索下一个字符。
  • 当遍历到待查单词的结尾时,如果当前结点的 isEnd = truecnt = 1,则返回 true

代码

class Trie {
private:
    bool isEnd;
    vector<Trie*> children;

public:
    Trie() : children(26), isEnd(false) {}

    void insert(const string& word) {
        Trie* node = this;
        for (const auto& ch: word) {
            int idx = ch - 'a';
            if (node->children[idx] == nullptr) {
                node->children[idx] = new Trie();
            }
            node = node->children[idx];
        }
        node->isEnd = true;
    }

    bool search(const string& word, int idx, int cnt) {
        if (cnt > 1) return false;
        Trie* node = this;
        if (idx == word.size()) return node->isEnd && cnt == 1;
        for (int i = 0; i < 26; ++i) {
            if (node->children[i] == nullptr) {
                continue;
            }
            int t = word[idx] - 'a' == i ? cnt : cnt + 1;
            if (node->children[i]->search(word, idx + 1, t)) {
                return true;
            }
        }
        return false;
    }
};
class MagicDictionary {
private:
    Trie* root;
public:
    MagicDictionary() {
        root = new Trie();
    }
    
    void buildDict(vector<string> dictionary) {
        for (const auto& s: dictionary) {
            root->insert(s);
        }
    }
    
    bool search(string searchWord) {
        return root->search(searchWord, 0, 0);
    }
};

文章作者: xitie2000
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 xitie2000 !
评论
  目录