LeetCode 387. First Unique Character in a String 字符串中的第一个唯一字符

链接

https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/

要求

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

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

相关代码

思路:
全部遍历会超出时间限制。
用set过滤掉重复字符后用sorted方法,并指定key = s.index来保持原先的字符串顺序

class Solution(object):
    def firstUniqChar(self, s):
        s_str = ''
        s_set = sorted(set(list(s)), key = s.index)
        for i in s_set:
            if s.count(i) == 1:
                s_str = i
                break

        if s and s_str:
            return s.index(s_str)
        else:
            return -1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容