题目:
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.
方法一:性能162ms
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters = {}
for c in s:
if c in letters:
letters[c] = letters[c] + 1
else:
letters[c] = 1
for i in xrange(len(s)):
if letters[s[i]] == 1:
return i
return -1
方法二:性能92ms
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in 'abcdefghijklmnopqrstuvwxyz' if s.count(c)==1] or [-1])
方法三: 性能75ms
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])