387. First Unique Character in a String
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.
思路:
因为set是无序的,所以set中第一个不重复的字符未必是输入字符串中的第一个,也可能是多个,将他们的index存储起来,返回最小的即可。
代码:
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
ch=[]
for i in set(s):
if s.count(i) == 1:
ch.append(s.index(i))
if len(ch)>0:
return min(ch)
else:
return -1