LN : leetcode 242 Valid Anagram

时间:2023-03-10 03:15:14
LN : leetcode 242 Valid Anagram

lc 242 Valid Anagram


242 Valid Anagram

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

For example,

s = "anagram", t = "nagaram", return true.

s = "rat", t = "car", return false.

analysation##

利用类似于带有26个桶的数组容器存放各个字母在字符串中出现的次数。

solution

bool isAnagram(char* s, char* t) {
int letters[26] = {0}, letters2[26] = {0};
int i, sum = 0, num = 0;
if (strlen(s) != strlen(t))
return false;
for (i = 0; i < strlen(s); i++) {
letters[s[i]-'a']++;
letters2[t[i]-'a']++;
num++;
}
for (i = 0; i < 26; i++) {
if (letters[i] == letters2[i])
sum += letters[i];
}
return (sum == num);
}