forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reformat-the-string.py
36 lines (31 loc) · 925 Bytes
/
reformat-the-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
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def reformat(self, s):
"""
:type s: str
:rtype: str
"""
def char_gen(start, end, count):
for c in xrange(ord(start), ord(end)+1):
c = chr(c)
for i in xrange(count[c]):
yield c
yield ''
count = collections.defaultdict(int)
alpha_cnt = 0
for c in s:
count[c] += 1
if c.isalpha():
alpha_cnt += 1
if abs(len(s)-2*alpha_cnt) > 1:
return ""
result = []
it1, it2 = char_gen('a', 'z', count), char_gen('0', '9', count)
if alpha_cnt < len(s)-alpha_cnt:
it1, it2 = it2, it1
while len(result) < len(s):
result.append(next(it1))
result.append(next(it2))
return "".join(result)