LeetCode练习——字符串(字符串中的第一个唯一字符)

这篇博客介绍了如何在Python中找到字符串中的第一个不重复字符。提供了四种解法:使用哈希表存储频数、存储索引、使用队列以及利用find和rfind方法。每种方法都通过遍历字符串并检查字符的出现频率或位置来找出第一个不重复的字符。示例和代码详细解释了实现过程。
摘要由CSDN通过智能技术生成

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

示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
提示:你可以假定该字符串只包含小写字母。

官方解法:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/zi-fu-chuan-zhong-de-di-yi-ge-wei-yi-zi-x9rok/

解法一:使用哈希表存储频数

class Solution:
    def firstUniqChar(self, s: str) -> int:
        frequency = collections.Counter(s)
        for i, ch in enumerate(s):
            if frequency[ch] == 1:
                return i
        return -1

解法二:使用哈希表存储索引

class Solution:
    def firstUniqChar(self, s: str) -> int:
        position = dict()
        n = len(s)
        for i, ch in enumerate(s):
            if ch in position:
                position[ch] = -1
            else:
                position[ch] = i
        first = n
        for pos in position.values():
            if pos != -1 and pos < first:
                first = pos
        if first == n:
            first = -1
        return first

解法三:队列

class Solution:
    def firstUniqChar(self, s: str) -> int:
        position = dict()
        q = collections.deque()
        n = len(s)
        for i, ch in enumerate(s):
            if ch not in position:
                position[ch] = i
                q.append((s[i], i))
            else:
                position[ch] = -1
                while q and position[q[0][0]] == -1:
                    q.popleft()
        return -1 if not q else q[0][1]

解法四:python的find和rfind

class Solution:
    def firstUniqChar(self, s: str) -> int:
        for x in s:
            if s.find(x) == s.rfind(x):
                return s.find(x)
        return -1

python字符串遍历方法:https://www.cnblogs.com/qa-freeroad/p/14100757.html

菜鸟教程:https://www.runoob.com/python/att-string-rfind.html
find() 是从字符串左边开始查询子字符串匹配到的第一个索引;
rfind()是从字符串右边开始查询字符串匹配到的第一个索引。返回字符串最后一次出现的位置,如果没有匹配项则返回-1。

力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值