Python实现"字符串中的第一个唯一字符"的两种方法

给定一个字符串,找到字符串中第一个不重复的字符,并返回它的下标。如果不存在不重复的字符,则返回-1

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

注意:

你可以假设字符串中只存在小写字母

1:用set()方法,将字符串s转为不包含重复字母的随机排列集合sStr。访问sStr,生成字典chaDic,字典中存放字母和其在字符串s中出现的次数(cha:num)。访问字符串s中元素,在chaDic中查询该元素对应的次数,如果次数为1就输出该元素在字符串s中对应的下标

def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        sSet = set(s)
        chaDic = {}
        for i in sSet:
            chaDic[i] = s.count(i)
        for i, j in enumerate(s):
            if chaDic.get(j) == 1:
                return i
        return -1

另一种更灵活的写法

def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        chaDic = {}
        for i, j in enumerate(s):
            if not chaDic.get(j):
                count = s[i:].count(j)
                if count == 1:
                    return i
                else:
                    chaDic[j] = count
        return -1

2:字符串s只包含小写字母共26个,故利用str.find()和str.rfind()方法解决(参考他人)

str.find(str, beg=0, end=len(string)):检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

str.rfind(str, beg=0 end=len(string)):返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。

def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        sinCha = []
        for i in "qwertyuiopasdfghjklzxcvbnm":
            start = s.find(i)
            end = s.rfind(i)
            if start != -1 and start == end:
                sinCha.append(start)
        if sinCha:
            return min(sinCha)
        return -1

str.count()+str.index(),一行优雅写法(参考他人)

def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1])

算法题来自:https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值