您的位置:首页 > 其它

LeetCode 387 字符串中的第一个唯一字符【简单】

2018-05-30 20:26 393 查看

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

题目描述:

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

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

案例:s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.注意事项:您可以假定该字符串只包含小写字母。个人解答如下,没有写注释,看起来有点乱...

104 / 104 个通过测试用例状态:

通过

执行用时:76 ms
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
list1=[]
list2=[]
if len(s)==1:
return 0
elif len(s)==2:
if s[0]==s[1]:
return -1
else:
return 0
elif len(s)!=0:
s1="".join(list(set(s)))
for i in s1:
if s.count(i)!=1:
continue
else:
list1.append(i)
if len(list1)==s1 or len(list1)==0:
return -1
else:
for j in list1:
list2.append(s.index(j))
a=sorted(list2)
return a[0]

else:
return -1

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: