-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcount-residue-prefixes.py
More file actions
41 lines (38 loc) · 939 Bytes
/
count-residue-prefixes.py
File metadata and controls
41 lines (38 loc) · 939 Bytes
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
# Time: O(n + 26)
# Space: O(26)
# hash table
class Solution(object):
def residuePrefixes(self, s):
"""
:type s: str
:rtype: int
"""
result = distinct = 0
lookup = [False]*26
for i, x in enumerate(s):
if not lookup[ord(x)-ord('a')]:
distinct += 1
if distinct >= 3:
break
lookup[ord(x)-ord('a')] = True
if distinct == (i+1)%3:
result += 1
return result
# Time: O(n)
# Space: O(3)
# hash table
class Solution2(object):
def residuePrefixes(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
lookup = set()
for i, x in enumerate(s):
lookup.add(x)
if len(lookup) >= 3:
break
if len(lookup) == (i+1)%3:
result += 1
return result