确定两个字符串是否接近-哈希表1657-c++

哈希表

#include <unordered_map>

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        // 先用哈希表分别记录每个字符串的字母出现次数:如果字母不同时存在于两个哈希表 直接返回false
        // 转换成出现次数为key,字母vec为value的哈希表
        // 判断同key下字母vec是长度是否相等:不相等或key不同时存在 直接返回false
        // 都ok就返回true
        if (word1.size() != word2.size()) {
            return false;
        }
        int n = word1.size();

        unordered_map<char, int> word1_map;
        unordered_map<char, int> word2_map;

        unordered_map<int, vector<char>> word1_count_map;
        unordered_map<int, vector<char>> word2_count_map;

        for (int i = 0; i < n; i++) {
            char s = word1[i];
            char t = word2[i];

            if (word1_map.count(s) > 0) {
                word1_map[s]++;
            } else {
                word1_map[s] = 1;
            }

            if (word2_map.count(t) > 0) {
                word2_map[t]++;
            } else {
                word2_map[t] = 1;
            }
        }

        for (const auto& it : word1_map) {
            char s = it.first;
            if (word2_map.count(s) == 0) {
                return false;
            }
        }

        word1_count_map = reverse_key_value(word1_map);
        word2_count_map = reverse_key_value(word2_map);

        for (const auto& it : word1_count_map) {
            int count = it.first;
            if (word2_count_map.count(count) == 0) {
                return false;
            } else if (word1_count_map[count].size() != word2_count_map[count].size()) {
                return false;
            }
        }

        return true;
    }

    unordered_map<int, vector<char>> reverse_key_value(unordered_map<char, int>& word_map) {
        unordered_map<int, vector<char>> word_count_map;
        for (const auto& it : word_map) {
            int count = it.second;
            char s = it.first;
            if (word_count_map.count(count) > 0) {
                word_count_map[count].emplace_back(s);
            } else {
                vector<char> s_vec;
                s_vec.emplace_back(s);
                word_count_map[count] = s_vec;
            }
        }
        return word_count_map;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值