题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
//首先通过哈希表存储字符串数组中各字符出现的次数,再对次数为1的进行输出,如果没有,则输出-1 #include <stdio.h> #include <string.h> int main() { char str[1001] = {0}; int len = 0; while(scanf("%s", str) != EOF) { len = strlen(str); int hash_table[127] = {0}; for(int i = 0; i<len; i++) //哈希存储出现次数 { hash_table[str[i]]++; } int flag = 0; for(int j = 0; j<len; j++) //对应数组中字符存储在哈希表中次数为1则输出,否则表示没有,输出-1 { if(hash_table[str[j]] == 1) { printf("%c\n",str[j]); flag = 1; break; } } if(!flag) printf("-1\n"); } return 0; }