首页 > 其他 > 详细

第一个只出现一次的字符

时间:2014-03-15 19:52:05      阅读:343      评论:0      收藏:0      [点我收藏+]
/**************************************************************************
题目:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出‘b‘。
**************************************************************************/
/*
解题思路:
我们可以定义哈希表的键值(Key)是字符,而值(value)是该字符出现的次数。同时
我们还需要从头开始扫描字符串两次。第一次扫描字符串时,每扫描到一个字符就在哈希
表的对应项中把次数加1。接下来第二次扫描时,每扫描到一个字符就能从哈希表中得到
字符出现的次数。这样第一个只出现一次的字符就是符合要求的输出。
*/
#include<stdio.h>

char firstNoRepeaChar(char* str)
{
	if(str == NULL)
		return ‘\0‘;

	const int tableSize = 256;
	unsigned int hashTable[tableSize];
	for(unsigned int i=0; i<tableSize; ++i)
		hashTable[i] = 0;

	char* pHashKey = str;
	while( *pHashKey != ‘\0‘)
		hashTable[*pHashKey++]++;

	pHashKey = str;
	while(*pHashKey != ‘\0‘)
	{
		if(hashTable[*pHashKey] == 1)
			return *pHashKey;
		++pHashKey;
	}
	return ‘\0‘;
}

void test()
{
	char* str = "abaccdeff";
	printf("%c\n",firstNoRepeaChar(str));
}
int main()
{	
	test();
	return 0;
}
==参考剑指offer

第一个只出现一次的字符,布布扣,bubuko.com

第一个只出现一次的字符

原文:http://blog.csdn.net/walkerkalr/article/details/21294759

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!