第一个只出现一次的字符

题目描述

来源于 https://leetcode-cn.com/

在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。

示例:

s = "abaccdeff"
返回 "b"

s = "" 
返回 " "

限制:

0 <= s 的长度 <= 50000

解法:

先遍历字符串,使用 map 记录下各个字符出现的次数。然后再次顺序遍历字符串,找出第一个出现一次的字符。

class Solution {
public:
    char firstUniqChar(string s) {
        unordered_map<char, int> mp;
        for(char ch: s){
            mp[ch] += 1;
        }
        for(char ch: s){
            if(mp[ch] == 1){
                return ch;
            }
        }
        return ' ';
    }
};