【LeetCode刷题(简单程度)】剑指 Offer 50. 第一个只出现一次的字符

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

示例:

s = “abaccdeff”
返回 “b”

s = “”
返回 " "

限制:

0 <= s 的长度 <= 50000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:使用哈希表实现,先存储每一个字符出现的次数,然后遍历字符,找出第一个次数为1的字符即可。

class Solution {
public:
    char firstUniqChar(string s) {
        int n = s.size();
        char res = ' ';
        if(n == 0)
            return res;
        unordered_map<char,int> table;
        for(int i = 0;i < n;++i)
        {
            table[s[i]]++;
        }
        char tmp;
        for(const auto &tmp: s)
        {
            if(table[tmp] == 1)
            {
                res = tmp;
                break;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33197518/article/details/109105802