给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回-1。
示例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意:可以假定该字符串只包含小写字母。
方法1:
思路:采用字典计数法,用collections.Counter()方法统计字符出现的次数,若只出现一次,返回其对应的索引,否则返回-1。
class Solution:
def firstUniqChar(self, s):
d = collections.Counter(s)
for i in range(len(s)):
if d[s[i]] == 1:
return i
return -1
方法2:
思路:将字符串转化为小写,然后用.count()方法统计只出现一次的字符的索引,并返回最小的一个,否则返回-1。
class Solution:
def firstUniqChar(self, s):
lowercase = string.ascii_lowercase
res = [s.index(label) for label in lowercase if s.count(label) == 1]
if len(res):
return min(res)
return -1