LeetCode387. First Unique Character in a String

本文探讨了在字符串中查找第一个不重复字符及其索引的有效算法。通过使用Python的Counter方法,文章提供了一种比简单遍历更高效的方法。此外,还介绍了一个更快的解决方案,该方案针对预定义的字母表进行了优化。

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.


思路:一开始的想法就是用count()方法遍历,找到第一个count为1的字母,如下面这种方法,不过这样会超时

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        for i,char in enumerate(s):
            if s.count(char)==1:
                return i
        return -1

然后想到利用collections的Counter()方法,先统计个数,再对个数为1的进行位置比较,返回第一个个数为1字母的位置。

from collections import Counter
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        min = float('inf')
        dic = Counter(s)

        for key,val in dic.items():
            if val==1:
                if min>s.index(key):
                    min = s.index(key)
        if min!=float('inf'):
            return min

        return -1

看了discuss,有更快的方法,不过要事先设好输入的letters。

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        letters='abcdefghijklmnopqrstuvwxyz'

        index=[s.index(l) for l in letters if s.count(l) == 1]

        return min(index) if len(index) > 0 else -1

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值