leetcode(51)-----387. 字符串中的第一个唯一字符

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

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

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


Python代码实现:
判断第一个字符是否唯一,不唯一就全删光,继续判断第一个字符,直到找出,
如果没有就返回-1
但超出时间限制:

class Solution:
    def firstUniqChar(self, s):
        ls = s[:]
        s= list(s)
        lenth = len(s)
        while lenth>0:
            k = s[0]
            s.remove(k)
            lenth -=1
            if k not in s:
                return ls.index(k)
            else:
                while k in s:
                    s.remove(k)
                    lenth -= 1
        return -1

改变一下思路:用双重循环,判断有没有相等的。

class Solution:
    def firstUniqChar(self, s):
        length = len(s)
        for i in range(length):
            for j in range(length):
                if s[i] == s[j] and i != j:
                    break          # 提前中断可以提高效率
                elif j == length-1 :
                    return i
        return -1

将字符串 转换成 列表, 再用字典统计每个元素的次数,将字典的每个键 放到一个数组的排好序,按照这个次数来找出第一个次数为 1 的字符。

class Solution:
    def firstUniqChar(self, s):
        number= []
        dic = {}
        for i in range(len(s)):
            if s[i] not in number:
                number.append(s[i])
                dic[s[i]] = 1
            else:
                dic[s[i]] += 1

        for j in range(len(number)):
            if dic.get(number[j]) == 1:
                for k in range(len(s)):
                    if s[k] == number[j]:
                        return k
        return -1

使用collection模块的Counter类:

class Solution(object):
    def firstUniqChar(self, s):

        dic=collections.Counter(s)#使用字典
        for i in range(len(s)):
            if dic[s[i]]==1:#如果字典中value为1
                return i
        return -1

Python标准库——collections模块的Counter类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值