LeetCode--387--字符串中的第一个唯一字符

问题描述:

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

案例:

s = "leetcode"
返回 0. s = "loveleetcode",
返回 2.

方法:

 class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
x = "abcdefghijklmnopqrstuvwxyz"
res = [] #res=[s.index[i] for i in x if s.count(i) == 1]
for i in x:
if i in s and s.count(i) == 1:
res.append(s.index(i))
if len(res):
return min(res)
return -1

官方:

 class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
""" if s == '':
return -1 l = len(s)
tmp = l
for i in 'abcdefghijklmnopqrstuvwxyz':
start = s.find(i)
end = s.rfind(i)
if start != -1 and start == end:
tmp = min(tmp, start)
if tmp < l:
return tmp
else:
return -1

2018-09-28 16:27:05

上一篇:maven 工作原理和添加jar包技巧


下一篇:[转]Delphi : keydown与keypress的区别,组合键