Leetcode First Unique Character in a String Python 列表中找到第一个只出现一次的第一个数字,如何计算字符出现次数。

Leetcode 387题 First Unique Character in a String
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. 假设字母全是小写。

一看不重复,其实就是只出现一次。自然就想到了.count()方法,和Counter函数。

思路一:

遍历字符串,然后单独计算出每个字符的重复次数,如果重复次数为1,说明这个数不重复。.index()方法求出这个字符在整个字符串的位置,存到列表中,最后求出列表中最小的数,就是第一个出现地不重复的字符的所在位置。

直接给代码。

class Solution:
    def firstUniqChar(self, s: str) -> int:
        res = []
        for i in set(s):
            if s.count(i) == 1:
                res.append(s.index(i))
        if len(res) != 0:
            return min(res)
        else:
            return -1

思路二:
改进一下,既然假设字母都是小写,干脆直接把小写字母的字典放上来。 思路一样。第二行省了定义index的步骤了。 不过这样速度会更快一点。字典复杂度低。

class Solution:
    def firstUniqChar(self, s: str) -> int:
        temp = "abcdefghijklmnopqrstuvwxyz"
        index = [s.index(i) for i in temp if s.count(i)==1]
        return min(index) if len(index)>0 else -1

疫情中的英国,
前段时间生病了,生活终于回到了正轨。
加油!
28/05/2020

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值