题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37
/*
思路: 两次遍历字符串,
1. 第一次统计每个字符出现的次数 借助数组 array<int,26> arr{0};
2. 第二次找到第一个只出现一次的字符
*/
#include <array>
#include <iostream>
using namespace std;
// 先遍历一遍数组,利用26个元素的数组来存放每个单词出现的次数
// 第二次再遍历一次数组,找到第一个出现一次的字符
int main() {
string str;
cin >> str;
array<int, 26> a{0};
int len = str.length();
for(int i = 0; i < len; ++i){
a[str[i] - 'a']++;
}
bool bisFound = false;
int pos = -1;
for(int i = 0; i < len; ++i){
if(1 == a[str[i] - 'a']){
bisFound = true;
pos = i;
break;
}
}
if(bisFound){
cout << str[pos] << endl;
}else{
cout << -1 << endl;
}
return 0;
}
// 64 位输出请用 printf("%lld")
