您的位置:首页 > 其它

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

2012-10-09 17:09 344 查看
在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。这个问题能够让我们想起hash表,因为包括汉字或者其他字符在内的所有字符都可以用16个bit也就是两个字节表示,所以总共有256个字节。要想求出一个字符串中第一个只出现一次的字符,首先是要统计每个字符出现的次数,然后在重新遍历字符数组,找到第一个hash表值为1的对应的字符。这也是hash表的应用。

#include<stdio.h>
#include<memory.h>
char find_first_unique_char(char *str)
{
int data[256];
char *p=str;
if(*p=='\0')
return '\0';
memset(data,0,sizeof(data));
while(*p!='\0')
data[*p++]++;
while(*str!='\0')
{
if(data[*str]==1)
return *str;
str++;
}
return '\0';
}
int main()
{
char *str = "aaddfeeehjjk";
printf("%c\n",find_first_unique_char(str));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐