[leetcoe] 387. First Unique Character in a String @ python

本文深入探讨了一种高效算法,用于在字符串中查找第一个不重复的字符,并详细解释了其实现过程。通过使用字典记录字符出现频率,再遍历字符串定位目标字符,此方法在时间和空间复杂度上表现优异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

s = “leetcode”
return 0.

s = “loveleetcode”,
return 2.
Note: You may assume the string contain only lowercase letters.

解法

先用字典存储每个字符出现的次数, 然后遍历字符串, 当出现字母次数为1时, 返回当前index.
Time: 2*O(n)
Space: O(1)

代码

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = collections.Counter(s)
        for i, char in enumerate(s):
            if count[char] == 1:
                return i
        return -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值