在一个字符串中找到第一个只出现一次的字符。

/**************************************

*copyright@ andy

*http://blog.csdn.net/MonkeyAndy

**************************************/

题目描述:

在一个字符串中找到第一个只出现一次的字符。如输入 abaccdeff,则输出 b。


思路:

用hash表来保存相应的字符,key为ch-‘a’, value为相应的出现的次数,遍历字符串,寻找对应的hash表中value为1所对应的字符


代码如下:

/********如有您有任何疑问及发现问题,欢迎随时指正********/

//copyright@andy
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define TABLESIZE 26

typedef struct HashTable{
	char *elem;
	int count;//当前hash表中的元素个数
	int size;//hash的容量
}HashTable;

HashTable h;
void init_hash()
{
	h.elem = (char*) malloc (sizeof(char) * TABLESIZE);

	if(!h.elem) exit(1);

	memset(h.elem, 0, TABLESIZE);
	h.count = 0;
	h.size = TABLESIZE;
}
char find_first_appear(char *string)
{
	int i;

	char *pstring = string;
	/*第一次遍历字符串,构建字符串相应的hash表,key为 ch-'a' ,value 为相应的出现的个数*/
	while(*pstring != '\0')
	{
		h.elem[*(pstring++) - 'a']++;
		h.count++;
	}
	/*第二次遍历字符串,找到第一个出现一次的字符*/
	while(*string++ != '\0')
	{
		if(h.elem[*string - 'a'] == 1)
			return *string;
	}
	/*没找到时,返回空*/
	return '\0';
}

int main()
{
	char * string="abaccdeff";
	int i;
	
	init_hash();
	char first_appear = find_first_appear(string);

	for(i=0; i<TABLESIZE; i++)
		printf("%c ",'a'+i);
	printf("\n");
	
	for(i=0; i<TABLESIZE; i++)
		printf("%d ",h.elem[i]);
	printf("\n");

	printf("the current size of hash table is %d\n
           the fist appear char is %c\n",h.count, first_appear);

	return 0;
}


参考自: http://blog.csdn.net/v_JULY_v   编程艺术系列 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值