-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy path1370-Increasing-Decreasing-String.py
More file actions
30 lines (28 loc) · 1.27 KB
/
1370-Increasing-Decreasing-String.py
File metadata and controls
30 lines (28 loc) · 1.27 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
'''
You are given a string s. Reorder the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return the result string after sorting s with this algorithm.
'''
class Solution:
def sortString(self, s: str) -> str:
s = list(s)
result = []
while s:
temp = list(set(s))
temp.sort(key=lambda c: ord(c))
for i in temp:
result.append(i)
s.remove(i)
temp = list(set(s))
temp.sort(key=lambda c: ord(c), reverse=True)
for i in temp:
result.append(i)
s.remove(i)
return ''.join(result)