C⼀C++编程题:查找字符串中第一个只出现一次的字符,例如字符串为“abaccde”,则输出b,两种算法实现

2025-03-04 03:25:05
推荐回答(2个)
回答1:

用哈希的方式,把字符在哈希表中统计出每一个的个数来,然后从小开始遍历出第一个为1的
代码如下:
#include
#include

char get_onlyone(char* str)
{
char i;
int hash[128];
memset(hash, 0, sizeof(hash));
for(i = 0; str[i]; i++) {
hash[str[i]]++;
}
for(i = 0; i < 128; i++) {
if(hash[i] == 1) break;
}
return i;
}

int main(void)
{
char str[128];
while(scanf("%s", str) != EOF) {
printf("%c\n", get_onlyone(str));
}
return 0;
}

回答2:

第一种用普通的数组记录某个字母出现的次数,遍历完字符串就知道哪个出现一次。
第二种可以用哈希思想,去判断某个字母是否出现多次,复杂度也是便利一边的时间