题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
#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")
查看7道真题和解析