Skip to content

Commit 9101566

Browse files
committed
Increasing Decreasing String
1 parent 08c7733 commit 9101566

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

1370-increasing-decreasing-string.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/increasing-decreasing-string/
3+
4+
Given a string s. You should re-order the string using the following algorithm:
5+
Pick the smallest character from s and append it to the result.
6+
Pick the smallest character from s which is greater than the last appended character to the result
7+
and append it.
8+
Repeat step 2 until you cannot pick more characters.
9+
Pick the largest character from s and append it to the result.
10+
Pick the largest character from s which is smaller than the last appended character to the result
11+
and append it.
12+
Repeat step 5 until you cannot pick more characters.
13+
Repeat the steps from 1 to 6 until you pick all characters from s.
14+
In each step, If the smallest or the largest character appears more than once you can choose
15+
any occurrence and append it to the result.
16+
Return the result string after sorting s with this algorithm.
17+
18+
Example 1:
19+
Input: s = "aaaabbbbcccc"
20+
Output: "abccbaabccba"
21+
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
22+
After steps 4, 5 and 6 of the first iteration, result = "abccba"
23+
First iteration is done. Now s = "aabbcc" and we go back to step 1
24+
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
25+
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
26+
27+
Example 2:
28+
Input: s = "rat"
29+
Output: "art"
30+
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
31+
32+
Example 3:
33+
Input: s = "leetcode"
34+
Output: "cdelotee"
35+
36+
Example 4:
37+
Input: s = "ggggggg"
38+
Output: "ggggggg"
39+
40+
Example 5:
41+
Input: s = "spo"
42+
Output: "ops"
43+
44+
Constraints:
45+
1 <= s.length <= 500
46+
s contains only lower-case English letters.
47+
"""
48+
class Solution:
49+
def sortString(self, s: str) -> str:
50+
alphabets = [0]*26
51+
for c in s:
52+
alphabets[ord(c) - ord('a')] += 1
53+
54+
res = []
55+
flag = direction = True
56+
index = 0
57+
while flag:
58+
flag = False
59+
while (index < len(alphabets) and direction) or (index >= 0 and not direction):
60+
if alphabets[index] > 0:
61+
res.append(chr(index + ord('a')))
62+
alphabets[index] -= 1
63+
flag = True
64+
index += 1 if direction else -1
65+
direction = False if direction else True
66+
index += 1 if direction else -1
67+
return "".join(res)

0 commit comments

Comments
 (0)