题目:
在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。
分析:
这道题是2006年google的一道笔试题。
ASCII码共有128个,所以可以建一个包含128个元素的数组,初始化为0。扫描字符串,出现某字符,就自增该字符
对应的ASCII值为下标的元素值!
代码如下:
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
int count[128];
-
-
void CountTimes(char *str);
-
-
int main()
-
{
-
char str[100];
-
while (printf("Please input a string : "),fgets(str,sizeof(str),stdin)!=NULL)
-
{
-
CountTimes(str);
-
}
-
-
return 0;
-
}
-
-
void CountTimes(char *str)
-
{
-
int len,i;
-
len=strlen(str)-1;
-
memset(count,0,sizeof(count));
-
-
for (i=0;i<len;i++)
-
{
-
count[str[i]]++;
-
}
-
-
-
-
-
-
-
for (i=0;i<len;i++)
-
{
-
if (count[str[i]]==1)
-
{
-
printf("The character which appears only once is : %c\n\n",str[i]);
-
return ;
-
}
-
}
-
-
}