LeetCode 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:

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

s = "loveleetcode",
return 2.

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

思路

Easy题打卡。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
for i in s:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
for i in range(len(s)):
if dic[s[i]] == 1:
return i
return -1