|
| 1 | +/** |
| 2 | + * 1370. Increasing Decreasing String |
| 3 | + * https://leetcode.com/problems/increasing-decreasing-string/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * You are given a string s. Reorder the string using the following algorithm: |
| 7 | + * 1. Remove the smallest character from s and append it to the result. |
| 8 | + * 2. Remove the smallest character from s that is greater than the last appended character, |
| 9 | + * and append it to the result. |
| 10 | + * 3. Repeat step 2 until no more characters can be removed. |
| 11 | + * 4. Remove the largest character from s and append it to the result. |
| 12 | + * 5. Remove the largest character from s that is smaller than the last appended character, |
| 13 | + * and append it to the result. |
| 14 | + * 6. Repeat step 5 until no more characters can be removed. |
| 15 | + * 7. Repeat steps 1 through 6 until all characters from s have been removed. |
| 16 | + * |
| 17 | + * If the smallest or largest character appears more than once, you may choose any occurrence to |
| 18 | + * append to the result. |
| 19 | + * |
| 20 | + * Return the resulting string after reordering s using this algorithm. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string} s |
| 25 | + * @return {string} |
| 26 | + */ |
| 27 | +var sortString = function(s) { |
| 28 | + const charCounts = new Array(26).fill(0); |
| 29 | + for (const char of s) { |
| 30 | + charCounts[char.charCodeAt(0) - 97]++; |
| 31 | + } |
| 32 | + |
| 33 | + let result = ''; |
| 34 | + while (result.length < s.length) { |
| 35 | + for (let i = 0; i < 26; i++) { |
| 36 | + if (charCounts[i] > 0) { |
| 37 | + result += String.fromCharCode(i + 97); |
| 38 | + charCounts[i]--; |
| 39 | + } |
| 40 | + } |
| 41 | + for (let i = 25; i >= 0; i--) { |
| 42 | + if (charCounts[i] > 0) { |
| 43 | + result += String.fromCharCode(i + 97); |
| 44 | + charCounts[i]--; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return result; |
| 50 | +}; |
0 commit comments