First Unique Character in a String

First Unique Character in a String

one line version

1
2
3
4
5
6
7
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])

slow version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from collections import OrderedDict
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
res = -1
hash_dict = OrderedDict()
for i in range(len(s)):
if s[i] in hash_dict:
hash_dict[s[i]] = (hash_dict[s[i]][0] + 1, i)
else:
hash_dict[s[i]] = (0, i)
for v in hash_dict.values():
if v[0] == 0:
res = v[1]
return res

output

1
2
3
4
In [604]: import string
In [605]: s = Solution(); print s.firstUniqChar('loveleetcode')
2

leet code