【打卡】第一个只出现一次的字符

阅读 133

2022-03-12

描述
给出一个字符串,找出第一个只出现一次的字符。假设只出现一次的字符数量大于等于1。

样例

Example 1:
	Input: "abaccdeff"
	Output:  'b'

	Explanation:
	There is only one 'b' and it is the first one.


Example 2:
	Input: "aabccd"
	Output:  'b'

	Explanation:
	'b' is the first one.

辅助数组记录字符出现次数。

class Solution:
    """
    @param str: str: the given string
    @return: char: the first unique character in a given string
    """
    def first_uniq_char(self, str: str) -> str:
        # Write your code here
        counter = {}

        for c in str:
            counter[c] = counter.get(c, 0) + 1   # dictionary.get(key,value)如果key不存在,则返回默认值value

        for c in str:
            if counter[c] == 1:
                return c

精彩评论(0)

0 0 举报