leetcode题解-242-有效的字母异位词

题目

My way

c++实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> m;

if (s.size() < t.size()) swap(s, t);

for (auto& it : s)
{
--m[it];
}

for (auto& it: t)
{
++m[it];
}

for (auto& it: m)
{
if (it.second != 0) return false;
}

return true;
}
};
  • 利用哈希表构成一个计数器的效果。
  • 利用ctor初始化int变量默认值是0,
    • s里出现过,则自减1;
    • t里出现过,则自增1;
  • 要注意,s, t字符串的大小可能不一样。所以需要在计数前,交换一次。

官方 way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;

int counter[26] = {0};

for (size_t i = 0; i < s.size(); ++i)
{
++counter[s[i] - 'a'];
--counter[t[i] - 'a'];
}

for (auto& it: counter)
{
if (it != 0) return false;
}

return true;
}
};
  • 利用一个int数组构造出一个计数器

References

https://leetcode-cn.com/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode/