Skip to content

Commit b8919fe

Browse files
authored
Create construct-string-with-repeat-limit.py
1 parent 3323cd1 commit b8919fe

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Time: O(26 * n)
2+
# Space: O(26)
3+
4+
import collections
5+
6+
7+
# greedy
8+
class Solution(object):
9+
def repeatLimitedString(self, s, repeatLimit):
10+
"""
11+
:type s: str
12+
:type repeatLimit: int
13+
:rtype: str
14+
"""
15+
cnt = collections.Counter(map(lambda x: ord(x)-ord('a'), s))
16+
result = []
17+
top1 = 25
18+
while True:
19+
top1 = next((i for i in reversed(xrange(top1+1)) if cnt[i]), -1)
20+
if top1 == -1:
21+
break
22+
c = min(cnt[top1], repeatLimit-int(len(result) > 0 and result[-1] == top1))
23+
cnt[top1] -= c
24+
result.extend([top1]*c)
25+
top2 = next((j for j in reversed(xrange(top1)) if cnt[j]), -1)
26+
if top2 == -1:
27+
break
28+
cnt[top2] -= 1
29+
result.append(top2)
30+
return "".join(map(lambda x: chr(x+ord('a')), result))

0 commit comments

Comments
 (0)