-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_unique_char.py
44 lines (39 loc) · 1.05 KB
/
first_unique_char.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from collections import defaultdict
class Solution:
"""
Task:
Given a string s, find the first non-repeating character in it and return its index.
If it does not exist, return -1.
"""
# Method 0
def firstUniqChar(self, s: str) -> int:
for i in s:
if s.rindex(i) == s.index(i):
return s.index(i)
return -1
# Method 1
def firstUniqChar(self, s: str) -> int:
d = defaultdict(int)
for word in s:
d[word] += 1
first = ""
for key in d:
if d[key] == 1:
first += key
break
for i, word in enumerate(s):
if word == first:
return i
return -1
# Method 2
def firstUniqChar(self, s: str) -> int:
seen = set()
for i in range(len(s)):
if s[i] in seen:
continue
try:
s.index(s[i], s.index(s[i], 0) + 1)
except:
return i
seen.add(s[i])
return -1