Skip to content

Commit 67a39d1

Browse files
authored
Create increasing-decreasing-string.py
1 parent 0da785e commit 67a39d1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def sortString(self, s):
6+
"""
7+
:type s: str
8+
:rtype: str
9+
"""
10+
result, count = [], [0]*26
11+
for c in s:
12+
count[ord(c)-ord('a')] += 1
13+
while len(result) != len(s):
14+
for c in xrange(len(count)):
15+
if not count[c]:
16+
continue
17+
result.append(chr(ord('a')+c))
18+
count[c] -= 1
19+
for c in reversed(xrange(len(count))):
20+
if not count[c]:
21+
continue
22+
result.append(chr(ord('a')+c))
23+
count[c] -= 1
24+
return "".join(result)
25+
26+
27+
# Time: O(n)
28+
# Space: O(1)
29+
import collections
30+
31+
32+
class Solution2(object):
33+
def sortString(self, s):
34+
"""
35+
:type s: str
36+
:rtype: str
37+
"""
38+
result, count, desc = [], collections.Counter(s), False
39+
while count:
40+
for c in sorted(count.keys(), reverse=desc):
41+
result.append(c)
42+
count[c] -= 1
43+
if not count[c]:
44+
del count[c]
45+
desc = not desc
46+
return "".join(result)
47+

0 commit comments

Comments
 (0)