forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
increasing-decreasing-string.py
47 lines (41 loc) · 1.15 KB
/
increasing-decreasing-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
# Time: O(n)
# Space: O(1)
class Solution(object):
def sortString(self, s):
"""
:type s: str
:rtype: str
"""
result, count = [], [0]*26
for c in s:
count[ord(c)-ord('a')] += 1
while len(result) != len(s):
for c in xrange(len(count)):
if not count[c]:
continue
result.append(chr(ord('a')+c))
count[c] -= 1
for c in reversed(xrange(len(count))):
if not count[c]:
continue
result.append(chr(ord('a')+c))
count[c] -= 1
return "".join(result)
# Time: O(n)
# Space: O(1)
import collections
class Solution2(object):
def sortString(self, s):
"""
:type s: str
:rtype: str
"""
result, count, desc = [], collections.Counter(s), False
while count:
for c in sorted(count.keys(), reverse=desc):
result.append(c)
count[c] -= 1
if not count[c]:
del count[c]
desc = not desc
return "".join(result)