LeetCode(剑指offer-hash table)-面试题50. 第一个只出现一次的字符

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

示例:

s = "abaccdeff"
返回 "b"
s = "" 
返回 " "

限制:

0 <= s 的长度 <= 50000

题源链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof

解题思路:hash map(key vale)
LeetCode(剑指offer-hash table)-面试题50. 第一个只出现一次的字符_第1张图片LeetCode(剑指offer-hash table)-面试题50. 第一个只出现一次的字符_第2张图片

class Solution:
    def firstUniqChar(self, s: str) -> str:
        dicts = {}
        for c in s:
            # if c in dicts:
            #     # c非第一次出现
            #     dicts[c] = False
            # else:
            #     # c第一次出现
            #     dicts = True
            dicts[c] = not c in dicts
        for c in s:
            if dicts[c]:
                return c
        
        return ' '
class Solution {
public:
    char firstUniqChar(string s) {
        unordered_map<char, int> counts;
        for (char c : s) {
            counts[c]++;
        }
        for (char c : s) {
            if (counts[c] == 1) {
                return c;
            }
        }

        return ' ';
    }
};

LeetCode(剑指offer-hash table)-面试题50. 第一个只出现一次的字符_第3张图片

你可能感兴趣的:(LeetCode)