面试题 06162012 [3]

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值