现在的位置: 首页 > 综合 > 正文

【4383】找出字符串中第一个出现最多的字符(华为入职前练习)

2013年03月12日 ⁄ 综合 ⁄ 共 919字 ⁄ 字号 评论关闭

思想:对于一串给定的字符串,利用int a[256],来获取字符串中每个字符出现的个数,然后对a数组进行处理,获取关于字符串的信息。

例如:char c=“!abcd ABCD!”,那么在a[256]中就有a[int(!)]=2,即“!”对应的ASCII码为33,a[33]=2,该字符串中有2个“!”。接下来以c字符串为索引,遍历int数组a,找出字符串中第一个出现最多的字符。


接口说明

原型:

bool FindChar(char* pInputString, char* pChar);

输入参数:

char* pInputString:字符串

输出参数(指针指向的内存区域保证有效):

char* pChar:出现次数最多的字符

返回值:

        false 异常失败

          true  输出成功

bool FindChar(char* pInputString, char* pChar)
{
	//在这里实现功能

	int hash[256]={0};
	int i=0;
	if(pInputString==NULL)
		return false;
	char *tmp=pInputString;

	while(*tmp)
	{
		hash[*(tmp++)]++;
	}
	
	tmp=pInputString;
	//寻找hash[]中第一个出现的最大值
	int max=1;//第*tmp个字符的个数
	while(*tmp)
	{
//		cout<<endl;
//		cout<<*tmp<<'\t'<<hash[*tmp]<<endl;
		if(hash[*tmp]<=max)
		{
			tmp++;
	//		continue;
		}
		else if(hash[*tmp]>max )
		{
			max=hash[*tmp];
			i=*tmp;
			tmp++;
		}
		else 
		{
				max=hash[*tmp];
				i=*tmp;
			break;
		}
	}

	*pChar=(char)i;//
//	cout<<endl;
//	cout<<"output the value:"<<endl;
//	cout<<*pChar<<endl;

	return true;
}

其实方法还是挺简单的,只是想慨叹一下,利用int数组处理字符串的问题,这个想法太神奇了,想到这点的大神简直让然崇拜的五体投地啊!!!

【上篇】
【下篇】

抱歉!评论已关闭.