/*
Write a function that returns whether one string is an anagram of another. A phrase is an anagram of another phrase if you can rearrange the letters of the first to form the second phrase, using all the original letters once.
Prototype: bool anagram_checker(const char* str1, const char* str2);
Test run: anagram_checker("George Bush", "He bugs Gore"); //this should return true
*/
#include <iostream>
char getRealChar(char c)
{
if(c >= 'A' && c <= 'Z')
{
int diff = c - 'A';
return 'a' + diff;
}
return c;
}
bool isAnagram(const char* str1, const char* str2)
{
int log[256];
memset(log, 0, sizeof(log));
for(int i = 0; i < strlen(str1); i++)
{
if(str1[i] != ' ')
{
log[getRealChar(str1[i])]++;
}
}
for(int i = 0; i < strlen(str2); i++)
{
if(str2[i] != ' ')
{
log[getRealChar(str2[i])]--;
}
}
for(int i = 0; i < 256; i++)
if(log[i] != 0)
return false;
return true;
};
int main()
{
const char* str1 = "George Bush";
const char* str2 = "He bugs Gore";
if(isAnagram(str1, str2))
printf("True");
else
printf("False");
return 0;
}
面试题 06162012 [3]
最新推荐文章于 2024-09-15 19:46:31 发布