题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
#include <stdio.h> #include <string.h> int main() { char str[1000] = {'\0'}; scanf("%s", str); int len = strlen(str); char letter[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; int ret[2][26]; for (int i = 0; i < 26; i++) { ret[0][i] = 0; ret[1][i] = 0; } for (int i = 0; i < 26; i++) { for (int j = 0; j < len; j++) { if (letter[i] == str[j]) { ret[0][i]++; ret[1][i] += j; } } } int onlyOneletter = 0; for (int i = 0; i < 26; i++) { if (ret[0][i] == 1) { onlyOneletter++; } } if (onlyOneletter == 0) { printf("-1"); return 0; } int ret_1[26]; for (int i = 0; i < 26; i++) { ret_1[i] = 1000; } for (int i = 0; i < 26; i++) { if (ret[0][i] == 1) { ret_1[i] = ret[1][i]; } } for (int i = 0; i < 26; i++) { for (int j = 0; j < 26 - i - 1; j++) { if (ret_1[j] > ret_1[j + 1]) { int temp = ret_1[j]; ret_1[j] = ret_1[j + 1]; ret_1[j + 1] = temp; } } } int result = ret_1[0]; printf("%c", str[result]); return 0; }