[LeetCode]#1370. Increasing Decreasing String
2 min readApr 27, 2020
Environment: Python 3.7
Key technique: lambda
Given a string s
. You should re-order 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.
Example 1:
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Analysis:
- Convert string to list
- use temp.sort(key=lambda c: ord(c)) to sort string according ord(string)
- ord(‘a’)=97,ord(‘b’)=98…
- So we can get [‘a’,’b’,’c’]
- add ‘a’,’b’,’c’ to ans list and remove them from input list
- use temp.sort(key=lambda c: ord(c), reverse=True) to get [‘c’,’b’,’a’]
- add ‘c’,’b’,’a’ to ans list and remove them from input list.
- When s string are removed, return answer.
Solution:
class Solution:
def sortString(self, s):
s = list(s)
ans = []
while s:
temp = list(set(s))
temp.sort(key=lambda c: ord(c))
for i in temp:
ans.append(i)
s.remove(i)
temp = list(set(s))
temp.sort(key=lambda c: ord(c), reverse=True)
for i in temp:
ans.append(i)
s.remove(i)
return ''.join(ans)
Submissions:
Lesson learn:
Below code can sort letter as a,b,c,d….
temp.sort(key=lambda c: ord(c))
Reference: