题解 | #找出字符串中第一个只出现一次的字符# 哈希表
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
map<char, int> se;
map<char,int> mp;
for(int i=0; i<n; i++){
// 统计出现的次数
if(mp.find(s[i]) == mp.end()){
mp[s[i]] = 1;
}else {
mp[s[i]]++;
}
// 统计出现的位置
if(se.find(s[i]) == se.end()){
se[s[i]] = i;
}
}
char res;
int loc = 2000;
for(auto i:mp){
if(i.second == 1){
if(se[i.first] < loc){
loc = se[i.first];
res = i.first;
}
}
}
if(loc == 2000){
cout << "-1" << endl;
return 0;
}
cout << res << endl;
return 0;
}
// 64 位输出请用 printf("%lld")
这道题的思路主要是基于对出现次数和第一次出现位置的统计,由于没有说字符串中只有字母,所以需要用到哈希表。
最终加上对于第一次出现位置的逻辑判断就好。
查看9道真题和解析
