剑指offer 51- 字符串中第一个只出现一次的字符

2021-05-30  本文已影响0人  顾子豪

在字符串中找出第一个只出现一次的字符。

如输入"abaccdeff",则输出b。

如果字符串中不存在只出现一次的字符,返回 # 字符。
样例:

输入:"abaccdeff"

输出:'b'

分析:
简单题
开一个Hash表用来存储每一个字符出现的次数。
时间复杂度:
O(N)

class Solution {
public:
    char firstNotRepeatingChar(string s) {
        unordered_map<char, int> hash;
        char res = '#';
        for(auto x : s) hash[x] ++;
        for(auto x : s) {
            if(hash[x] == 1) {
                res = x;
                break;
            }
        }
        return res;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读