面试题50:第一个只出现一次的字符
文章目录
题目
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
考点
双循环遍历字符串保证找到的是第一个出现次数为1的字符
map的使用 find,insert pair
LeetCode版本
class Solution {
public:
char firstUniqChar(string s) {
if(s.empty()) return ' ';
map<char,int> countMap;
for(int i= 0; i < s.size();i++){
if(countMap.find(s[i]) != countMap.end()){
countMap[s[i]]++;//访问map元素用[]
}else{
countMap.insert(pair<char,int>(s[i],1));
}
}
char res = ' ';//如果都是重复的,结果为' '
for(int i = 0 ; i < s.size(); i ++){
if(countMap[s[i]] == 1){
res = s[i];
break;
}
}
return res;
}
};