LeetCode - Implement Magic Dictionary

本文介绍了一种名为“魔法字典”的数据结构实现方法,通过两种不同的数据结构——unordered_map 和 unordered_set,实现了单词检索功能。当修改输入单词中的一个字符时,能够判断修改后的单词是否存在于字典中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解法一:unordered_map<int, vector<string>>

change one character to a word in the dictionary (same length)

class MagicDictionary {
public:
    /** Initialize your data structure here. */
    MagicDictionary() {
        
    }
    
    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for(string w: dict){
            m[w.size()].push_back(w);
        }
    }
    
    /** 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 w: m[word.size()]){
            int cnt=0, i=0;
            for(;i<word.size();i++){
                if(w[i]!=word[i]) cnt++;
                if(cnt==2) break;
            }
            if(cnt==1) return true;
        }
        return false;
    }
private:
    unordered_map<int, vector<string>> m;
};

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

解法二:unordered_set<string>

class MagicDictionary {
public:
    /** Initialize your data structure here. */
    MagicDictionary() {
        
    }
    
    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for(string w: dict){
            s.insert(w);
        }
    }
    
    /** 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 cur = word[i];
            for(char c='a'; c<='z';c++){
                if(c==cur) continue;
                word[i] = c;
                if(s.count(word)) return true;
            }
            word[i] = cur;
        }
        return false;
    }
private:
    unordered_set<string> s;
};

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值