链接:https://leetcode.cn/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
题目: 在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例 1:
输入:s = "abaccdeff"
输出:'b'
示例 2:
输入:s = ""
输出:' '
解题思路:借助map容器的记录词频,统计字符出现次数,遇到一次的字符,直接返回。
代码:
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<int, int> map;
for(char ch: s) {
++map[ch];
}
for(int i = 0; i < s.size(); i++) {
if(map[s[i]] == 1) return s[i];
}
return ' ';
}
};