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;
}

本文介绍了一个用于检查两个单词是否为字谜(anagram)的C++函数。该函数通过比较两个单词的字符频率来确定它们是否由相同的字母组成,尽管顺序不同。通过使用一个大小为128的数组作为哈希表来计数每个字符出现的次数,实现了高效且简洁的解决方案。
152

被折叠的 条评论
为什么被折叠?



