#1370

Increasing Decreasing String

newbie · 275 · lc easy +19 · verified · 77.2% accepted · 840 likes · top 88%

Description

You are given a string s. Reorder it using the following algorithm:

- Remove the smallest character from s and append it to the result.

- Remove the next smallest character that is greater than the last appended character, and append it.

- Repeat step 2 until no character can be selected.

- Remove the largest remaining character and append it.

- Remove the next largest character that is smaller than the last appended character, and append it.

- Repeat step 5 until no character can be selected.

- Repeat steps 1 through 6 until all characters are placed.

If the smallest or largest character has duplicates, any copy may be chosen. Return the resulting string.

Example 1:

Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"

Example 2:

Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.

Code

1
2
3