代码随想录额外题目| 哈希 ●205同构字符串 ●1002查找常用字符

#205同构字符串 easy

我是用的一个map和一个set

bool isIsomorphic(string s, string t) {
        unordered_set<char> letters;
        unordered_map<char,char> charmap;
        for(int i=0;i<s.size();i++){
            if(!charmap[s[i]] && letters.find(t[i])==letters.end()){
                charmap[s[i]]=t[i];
                letters.insert(t[i]);
            }
            else if(!charmap[s[i]] && letters.find(t[i])!=letters.end()) return false;
            else if(charmap[s[i]]!=t[i]) return false;
        }
        return true;
    }

随想录用的两个map记录互相的映射:

bool isIsomorphic(string s, string t) {
        unordered_map<char, char> map1;
        unordered_map<char, char> map2;
        for (int i = 0, j = 0; i < s.size(); i++, j++) {
            if (map1.find(s[i]) == map1.end()) { // map1保存s[i] 到 t[j]的映射
                map1[s[i]] = t[j];
            }
            if (map2.find(t[j]) == map2.end()) { // map2保存t[j] 到 s[i]的映射
                map2[t[j]] = s[i];
            }
            // 发现映射 对应不上,立刻返回false
            if (map1[s[i]] != t[j] || map2[t[j]] != s[i]) {
                return false;
            }
        }
        return true;
    }

#1002查找常用字符 easy

easy题但自己没做出来,一开始审题不认真以为是没有重复的,那个我会做

然后有重复的就想不明白。

下面是随想录的思路,看懂了,偷懒了没自己写(这种题也好做实现)

先求出第一个word里面各个字母个数。然后后面每个other word求各个字母个数,和第一个取小,所以取到最后答案就是最小的。ary初始化不会写,学了一下:int hashOtherStr[26] = {0}; 

这个全部赋值的写法:memset(hashOtherStr, 0, 26 * sizeof(int));

    vector<string> commonChars(vector<string>& A) {
        vector<string> result;
        
        int hash[26] = {0}; 
        for (int i = 0; i < A[0].size(); i++) { 
            hash[A[0][i] - 'a']++;
        }

        int hashOtherStr[26] = {0}; 
        for (int i = 1; i < A.size(); i++) {
            memset(hashOtherStr, 0, 26 * sizeof(int));
            for (int j = 0; j < A[i].size(); j++) {
                hashOtherStr[A[i][j] - 'a']++;
            }
            
            for (int k = 0; k < 26; k++) {
                hash[k] = min(hash[k], hashOtherStr[k]);
            }
        }
        
        for (int i = 0; i < 26; i++) {
            while (hash[i] != 0) { 
                string s(1, i + 'a'); 
                result.push_back(s);
                hash[i]--;
            }
        }

        return result;
    } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值