剑指offer 第一个只出现一次的字符 python

版权声明:本文为博主原创文章,需转载可以私信我,同意后即可 https://blog.csdn.net/Sun_White_Boy/article/details/83351323

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

样例

输入google
输出4

想法:
第一回遍历一次生成字典,第二回遍历找到值对应的index

class Solution:
    def FirstNotRepeatingChar(self, s):
        c = {}
        for i in s:
            if i in c:
                c[i] += 1
            else:
                c[i] = 1
        for index, i in enumerate(s):
            if c[i] is 1:
                return index
        return -1

    # 一行版本
    # 找到了一个Bug 如果无出现一次的数 则报错
    def FirstNotRepeatingChar_onerow(self, s):
        return s.index(list(filter(lambda x: s.count(x) == 1, s))[0]) if s else -1


最后

刷过的LeetCode或剑指offer源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

猜你喜欢

转载自blog.csdn.net/Sun_White_Boy/article/details/83351323