LeetCode 387 字符串中的第一个唯一字符【简单】

本文介绍了一个Python实现的方法,用于在给定字符串中找到并返回第一个唯一字符的位置索引。如果字符串中所有字符都重复出现,则返回-1。该算法首先统计每个字符的出现次数,然后遍历统计结果来确定首个唯一字符。

387字符串中的第一个唯一字符

题目描述:

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

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

个人解答如下,没有写注释,看起来有点乱...

104 / 104 个通过测试用例
状态:
通过
执行用时:76 ms
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        list1=[]
        list2=[]
        if len(s)==1:
            return 0
        elif len(s)==2:
            if s[0]==s[1]:
                return -1
            else:
                return 0
        elif len(s)!=0:
            s1="".join(list(set(s)))
            for i in s1:
                if s.count(i)!=1:
                    continue
                else:
                    list1.append(i)
            if len(list1)==s1 or len(list1)==0:
                return -1
            else:
                for j in list1:
                    list2.append(s.index(j))
                a=sorted(list2)
                return a[0]
                
        else:
            return -1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值