您的位置:首页 > 其它

判断两个字符串是不是互为anagrams

2016-04-12 10:07 288 查看
Description

Write a function that checks whether two words are anagrams. Two words are anagrams if they contain the same letters in any order. For example, “silent” and “listen” are anagrams. The header of the function is as follows:

bool isAnagram(const char * const s1, const char * const s2)

代码实现:

#include<iostream>
#include<string.h>
using namespace std;

bool isAnagram(const char * const s1, const char * const s2)
{
if(s1 == NULL || s2 == NULL){
return false;
}

int len1 = strlen(s1);
int len2 = strlen(s2);
if(len1 != len2)
return false;

int flag = true;
//使用哈希表来判断,因为只有字符串中最多只有128个不同的字符
//所以可以建立一个array[128]的哈希表
int array[128] = {0};
for(int i = 0; i < len1; i++){
array[*(s1+i)]++;
}
for(int i = 0; i < len1; i++){
array[*(s2+i)]--;
}

for(int i = 0; i < 128; i++){
if(array[i] != 0){
flag = false;
break;
}
}

return flag;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: