387. First Unique Character in a String
Easy
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.
笔记:
collection模块的Counter函数可以用来统计数字。获取一个可迭代对象(s)的索引,可以使用s.index()
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
num_letter = {}
for letter in s:
if letter in num_letter:
num_letter[letter] += 1
else:
num_letter[letter] = 1
for index, letter in enumerate(s):
if num_letter[letter] == 1:
return index
return -1
========================================================
#use Counter
import collections
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
mydict = collections.Counter(s)
for i in s:
if mydict[i] == 1:
return s.index(i)
return -1