题目:
找出字符串中第一个只出现一次的字符
输入描述:
输入一个非空字符串
输出描述:
输出第一个只出现一次的字符,如果不存在输出-1
示例1
输入
asdfasdfo
输出
o
解题思路:
和找出一个数组中只出现一次的数字方法类似,都是利用哈希表的思想来统计每个字符或数字出现的次数。然后在进行遍历,以返回只出现一次的数字或字符。
这个题的难点主要在于要自己设计main函数用来打印结果。值得注意的是,在这种题目中一定要循环的输入数据,打印结果。
代码实现:
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
char find(char str[], int len)
{
int i = 0;
int count[256] = {0};
for(i = 0; i < len; ++i)
{
count[str[i]]++;
}
for(i = 0; i < len; ++i)
{
if(count[str[i]] == 1)
return str[i];
}
return -1;
}
int main()
{
char str[1024];
while(cin>>str)
{
char ret = find(str, strlen(str));
if(ret >= 0 && ret <= 256)
printf("%c\n", ret);
else
printf("%d\n", (int)ret);
}
}