leetcode 387. First Unique Character in a String 详解 python3

一.问题描述

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.

二.解题思路

这道题如果单纯只是打算ac的话是很简单的。

用字典记录每个字符第一次出现的位置。

循环里每次判断现在的字符是否在dict中,不在说明第一次出现,记录位置,在的话说明是重复元素,把value随便改成个不可能出现的值。

之后 再来一次循环找出 value不为那个不可能值的值就好了。

时间复杂度O(2N),空间复杂度O(N)

但是提交 之后发现代码速度只排在60%左右(120ms),甚至发现有28ms的答案,表示十分好奇。

发现28ms的答案是把26个字符列出来,对每个字母,找出它左边第一次出现和右边第一次出现的位置,如果位置相等说明第一次出现,如果位置不等说明有重复。

表面看起来这需要O(26N),因为对每个字母都遍历,但是考虑到实际的情况,对于一个超长的字符串,因为我们只是找左边和右边第一次出现该字符的位置,只找到该位置为止就停止迭代,因此很可能我们根本就没迭代整个字符串,甚至迭代量远远小于字符串长度。这就是为啥它快的原因。而且考虑到字符在字符串中真实的分布,这样确实也合理一些。

critical thinking!不能只看单单的复杂度分析,还要考虑实际可能的数据分布。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

1.

class Solution:
    def firstUniqChar(self, s: str) -> int:
        res,ch2index=-1,{}
        for i in range(len(s)):
            if s[i] in ch2index:ch2index[s[i]]=-1
            else:ch2index[s[i]]=i
        for ch in s:
            if ch2index[ch]!=-1:return ch2index[ch]
        return res

2 声明:本代码出自leetcode样例。

class Solution:
    def firstUniqChar(self, s: str) -> int:
        res,ch2index=-1,{}
        for i in range(len(s)):
            if s[i] in ch2index:ch2index[s[i]]=-1
            else:ch2index[s[i]]=i
        for ch in s:
            if ch2index[ch]!=-1:return ch2index[ch]
        return res
发布了218 篇原创文章 · 获赞 191 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/CSerwangjun/article/details/103076127