-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmerge-close-characters.py
More file actions
41 lines (38 loc) · 1.01 KB
/
merge-close-characters.py
File metadata and controls
41 lines (38 loc) · 1.01 KB
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)
# simulation, hash table
class Solution(object):
def mergeCharacters(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
result = []
lookup = [-1]*26
for x in s:
if lookup[ord(x)-ord('a')] != -1 and len(result)-lookup[ord(x)-ord('a')] <= k:
continue
lookup[ord(x)-ord('a')] = len(result)
result.append(x)
return "".join(result)
# Time: O(n + 26)
# Space: O(26)
# simulation, freq table, two pointers
class Solution2(object):
def mergeCharacters(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
result = []
cnt = [0]*26
for x in s:
if cnt[ord(x)-ord('a')]:
continue
cnt[ord(x)-ord('a')] += 1
result.append(x)
if len(result) >= k+1:
cnt[ord(result[-(k+1)])-ord('a')] -= 1
return "".join(result)