-
Notifications
You must be signed in to change notification settings - Fork 43
/
first-unique-character-in-a-string.py
125 lines (105 loc) · 2.69 KB
/
first-unique-character-in-a-string.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
387. First Unique Character in a String
Easy
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Example 1:
Input: s = "leetcode"
Output: 0
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
Constraints:
1 <= s.length <= 105
s consists of only lowercase English letters.
"""
# V0
import collections
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = collections.Counter(s)
ans = -1
for x, c in enumerate(s):
if d[c] == 1:
ans = x
break
return ans
# V1
# http://bookshadow.com/weblog/2016/08/21/leetcode-first-unique-character-in-a-string/
import collections
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = collections.Counter(s)
ans = -1
for x, c in enumerate(s):
if d[c] == 1:
ans = x
break
return ans
# V1'
# https://www.jiuzhang.com/solution/first-unique-character-in-a-string/#tag-highlight-lang-python
class Solution:
"""
@param str: str: the given string
@return: char: the first unique character in a given string
"""
def firstUniqChar(self, str):
counter = {}
for c in str:
counter[c] = counter.get(c, 0) + 1
for c in str:
if counter[c] == 1:
return c
# V2
class Solution(object):
def firstUniqChar(self, s):
s_ = ''.join(set(s))
non_uniq_list = set([ x for x in s_ if s.count(x) > 1 ])
for i,j in enumerate(s):
if j in non_uniq_list:
pass
else:
return i
return -1
# V3
# IDEA : hash table
class Solution(object):
def firstUniqChar(self, s):
counts = {}
for i, j in enumerate(s):
if j in counts:
counts[j] += 1
else:
counts[j] = 1
print (counts)
for i, j in enumerate(s):
if counts[s[i]] == 1:
return i
return -1
# V4
from collections import defaultdict
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lookup = defaultdict(int)
candidtates = set()
for i, c in enumerate(s):
if lookup[c]:
candidtates.discard(lookup[c])
else:
lookup[c] = i+1
candidtates.add(i+1)
return min(candidtates)-1 if candidtates else -1