剑指offer 50-题 python题解记录

题50:第一个只出现一次的字符

法一:我以为我想的是个牛气方法,结果了
虽然代码行数很少,但每次count都会遍历一遍s

class Solution:
    def firstUniqChar(self, s: str) -> str:
        for i in s:
            if s.count(i)==1:
                return i
        return " "

法二:正解是用字典记录下每个字符出现的次数,再返回第一个只出现一次的字符

class Solution:
    def firstUniqChar(self, s: str) -> str:
        dic={
     }
        for i in s:
            if i not in dic:
                dic[i]=1
            else:
                dic[i]+=1
        for k in dic:
            if dic[k]==1:
                return k
        return " "

简洁版:
太厉害了,如果字符已经在字典中了,那么其值为0,否则为1

class Solution:
    def firstUniqChar(self, s: str) -> str:
        dic={
     }
        for i in s:
            dic[i]=not i in dic
        for k in dic:
            if dic[k]==1:
                return k
        return " "

你可能感兴趣的:(编程题)