【剑指offer】面试题50. 第一个只出现一次的字符

问题描述

面试题50. 第一个只出现一次的字符

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

示例:

s = "abaccdeff"
返回 "b"

s = ""
返回 " "

分析

使用哈希表进行词频统计然后输出即可

解题

1.使用库函数 collections.Counter

class Solution:
    def firstUniqChar(self, s: str) -> str:
        a=collections.Counter(s)
        for i,j  in a.items():
            if j==1:
                return i
        return ' '

2.自己写哈希表

class Solution:
    def firstUniqChar(self, s: str) -> str:

        # a={}
        # for i in s:
        #     if i in a:
        #         a[i] = 1
        #     else:
        #         a[i] = 0
        # for i in s:
        #     if a[i] ==0:
        #         return i
        # return ' '


        dic = {}
        for c in s:
            dic[c] = not c in dic
        for c in s:
            if dic[c]: return c
        return ' '

同样哈希的有剑指offer39题


原文地址:https://www.cnblogs.com/fuj905/p/12901001.html