您的位置:首页 > 编程语言 > C语言/C++

[leetcode]Valid Anagram C语言

2015-08-29 15:23 316 查看
【题目】

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.

【题目分析】

这道题就是判断s,t两个字符串里所含的每一种字母个数是否一样,一样,则返回true,不一样则返回false。采用的办法是用一个int check_s[26]来记录每个字母的个数。一次遍历,对于s中出现的字母,对应的check_s数组中元素加1,对于t中出现的字母,对应的check_s数组中元素减一,最后,判断check_s中所有元素是否全部是0,有非0,返回false,否则,返回true.

【具体代码如下】

bool isAnagram(char* s, char* t) {
int check_s[26]={0};
int i;
int indexs;
int indext;
for(i=0;(s[i]!='\0')||(t[i]!='\0');i++)
{
indexs=s[i]-'a';
check_s[indexs]++;
indext=t[i]-'a';
check_s[indext]--;
}
for(i=25;i>=0;i--)
{
if(check_s[i]!=0)
return false;
}
return true;

}


【个人总结】

一开始,我是用了两个数组分别记录s,t中所含字母的情况。后来进一步思考,减小了空间使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: