題目
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.
難度
Easy
方法
先用一個dict統(tǒng)計每個單詞出現(xiàn)的次數(shù),然后從頭開始檢查s
的字符搁骑,如果字符出現(xiàn)次數(shù)為1
卖鲤,則返回該字符的位置; 如果所有字符出現(xiàn)字數(shù)都不為1
清钥,則返回-1
python代碼
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
counter = {}
for c in s:
if counter.has_key(c):
counter[c] += 1
else:
counter[c] = 1
for i in range(len(s)):
if counter[s[i]] == 1:
return i
return -1
assert Solution().firstUniqChar("leetcode") == 0
assert Solution().firstUniqChar("leveleetcode") == 2