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

来源:互联网 发布:index.php 编辑:程序博客网 时间:2024/05/17 04:04

在一个字符串中找到第一个只出现一次的字符。如输入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; }