(Leetcode) 字符串中的第一个唯一字符 - Python实现

题目:字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode",返回 0.
s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。

-------------------------------------------------------------------------------------------------------------

解法1:字典统计字符频率

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {}
        for str in s:
            if str not in dic.keys():
                dic[str] = 1
            else:
                dic[str] += 1

        for i in range(len(s)):
            if dic[s[i]] == 1:
                return i
        return -1
               

解法2:通过collections中的Counter()方法

count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

count()方法语法:str.count(sub, start= 0,end=len(string))

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """

        import collections

        dic = collections.Counter(s)
        for i in range(len(s)):
            if dic[s[i]] == 1:
                return i
        return -1

解法3:解法2的优雅版(利用了都是小写字母的条件)

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """

        lowercase = 'abcdefghijklmnopqrstuvwxyz'

        res = [s.index(label) for label in lowercase if s.count(label) == 1]
        if len(res):
            return min(res)

        return -1

 

解法4:网友提供了一个妙法,切片。虽然效率不高,但很有意思。

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """

        for i in range(len(s)):
            str = s[:i] + s[i+1:]
            if s[i] not in str:
                return i
        return -1

参考

https://www.runoob.com/python/att-string-count.html

https://blog.csdn.net/IT_job/article/details/80417585

https://blog.csdn.net/zhenghaitian/article/details/80949209

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值