leetcode387: first unique character in a string 2. Analysis 3. Solution(s)

Link

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

1
2
3
4
5
s = "leetcode"
return 0
s = "loveleetcode"
return 2

Note: You may assume the string contain only lowercase letters.

2. Analysis

3. Solution(s)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class (object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dic = dict()
for i in s:
try:
dic[i] += 1
except:
dic[i] = 1
for index, element in enumerate(s):
if dic[element] == 1:
return index
return -1