您的位置:首页 > 其它

LeetCode算法第5篇:242 Valid Anagram

2015-09-22 09:18 337 查看
问题描述:

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法