LeetCode242 Valid Anagram


描述

Given two strings s and t, write a function to determine if t is an anagram of s.

Note:
You may assume the string contains only lowercase alphabets.

样例

1
2
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

思路

判断两个字符串是否“相等”(即字符的顺序不重要,只需比较每个字符的个数)。

模拟,用cnt数组记录每个字符的个数,比较下即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool isAnagram(string s, string t) {
int cnt1[26] = {0};
int cnt2[26] = {0};
for (char c: s) cnt1[c-'a']++;
for (char c: t) cnt2[c-'a']++;
for (int i = 0; i < 26; ++i) {
if (cnt1[i] != cnt2[i]) return false;
}
return true;
}
};