问题描述:
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.
Note:
You may assume the string contains only lowercase alphabets.
代码实现:
bool isAnagram(char* s, char* t) {
int i, length, map[26];
if (strlen(s) != strlen(t))
return false;
length = strlen(s);
memset(map, 0, sizeof(map));
for (i = 0; i < length; i++)
map[s[i]-'a']++;
for (i = 0; i < length; i++)
{
if (--map[t[i]-'a'] < 0)
return false;
}
return true;
}
总结:就是比较两个字符串中每个字母出现的次数是否一样,因为字符串中只有小写字母,所以定义一个大小为26的数组记录字符串s中每个字符出现的次数,然后再遍历字符串t。