代码随想录 242. 有效的字母异位词

70 阅读1分钟

242. 有效的字母异位词 - 力扣(LeetCode)

看到这个题的第一想法是用map

map哈希

class Solution {
public:
    bool isAnagram(string s, string t) {
    unordered_map<string,int> m1;
    unordered_map<string,int> m2;
    for(auto ch:s)
    {
        m1[ch]++;
    }
    for(auto hc:t)
    {
        m2[hc]++;
    }


if(m1.second==m2.second)return true;

return false;

    }
};

image.png

  1. The use of unordered_map<string, int> is incorrect as the keys are characters, not strings. It should be unordered_map<char, int> instead.
  2. The comparison m1.second == m2.second is incorrect. It should be comparing the entire map, not just the second member.

因为我们想要比较两个字符串中每个字符的数量是否相同,而不仅仅是比较字符和数量的组合。通过比较整个m1和m2,我们可以确保两个字符串中每个字符的数量都是相同的,从而判断它们是否是字母异位词。如果只比较second,只保证了数量相同,但是字符串却不一定相同。

如: s1:a b c s2: b c d a的数量1 b的数量1 数量相等了,但是a和b不是同一个字符。

Here's the corrected code:

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> m1;
        unordered_map<char, int> m2;
        
        for (auto ch : s) {
            m1[ch]++;
        }
        for (auto hc : t) {
            m2[hc]++;
        }

        return m1 == m2;
    }
};