/**************************************
*copyright@ andy
*http://blog.youkuaiyun.com/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.youkuaiyun.com/v_JULY_v 编程艺术系列