ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Google] LeetCode 1554 Strings Differ by One Character 哈希

2022-09-07 06:00:22  阅读:288  来源: 互联网

标签:Differ Google return 1554 int begin dict 哈希 true


Given a list of strings dict where all the strings are of the same length.

Return true if there are 2 strings that only differ by 1 character in the same index, otherwise return false.

Solution

对于每个字符串,我们用哈希将其映射为数。然后对于每个位置(即删除的位置),我们枚举每个字符串,得到该字符串删去该位置之后的哈希值。这里我们用一个 \(map\) 来存储此时哈希值对应的字符串下标。所以我们就可以在 \(map\) 里面查找其对应的下标,如果相同的话,那么就是 \(true\)

点击查看代码
class Solution {
private:
    int mod = 1e9+7;
    vector<long long> hash;
    int p = 37;
public:
    bool differByOne(vector<string>& dict) {
        int n=dict.size();
        int m = dict[0].size();
        hash = vector<long long> (n,0);
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                hash[i]=(long long)(p*hash[i]+(dict[i][j]-'a'))%mod;
            }
        }
        
        for(long long j=m-1, bs = 1;j>=0;j--){
            // hash_val -> pos
            unordered_map<long long,vector<long long>> mp;
            for(long long i=0;i<n;i++){
                long long res = (mod+hash[i]-bs*(dict[i][j]-'a')%mod)%mod;
                if(mp.find(res)!=mp.end()){
                    auto f = mp.find(res);
                    for(auto ele:f->second){
                        if(equal(begin(dict[i]),begin(dict[i])+j, begin(dict[ele])) && equal(begin(dict[i])+j+1, end(dict[i]), begin(dict[ele])+j+1))
                            return true;
                    }
                }
                mp[res].push_back(i);
            }
            bs=bs*p%mod;
        }
        return false;
    }
};





标签:Differ,Google,return,1554,int,begin,dict,哈希,true
来源: https://www.cnblogs.com/xinyu04/p/16663942.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有