美文网首页
LeetCode 387. First Unique Chara

LeetCode 387. First Unique Chara

作者: singed | 来源:发表于2018-08-27 15:02 被阅读0次

链接

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

相关文章

网友评论

      本文标题:LeetCode 387. First Unique Chara

      本文链接:https://www.haomeiwen.com/subject/bpttwftx.html