Question:


Method: first count the letters in order, and then forward and reverse traversal, if the number is not 0, then add changed letters in the result, and subtract 1, otherwise directly skip, the final output results can be.

package com.eric.leetcode class IncreasingDecreasingString { fun sortString(s: String): String { val arr = IntArray(26) { 0 } for (ch in s) { arr[ch - 'a'] += 1 } val result = StringBuilder() while (result.length ! = s.length) { for (el in arr.withIndex()) { if (el.value ! = 0) { arr[el.index] -= 1 result.append('a'.plus(el.index)) } } for (index in arr.lastIndex downTo 0) { val count = arr[index] if (count ! = 0) { arr[index] -= 1 result.append('a'.plus(index)) } } } return result.toString() } } fun main() { val increasingDecreasingString = IncreasingDecreasingString() print(increasingDecreasingString.sortString("rat")) }Copy the code

Feel free to communicate if you have any questions

Specific code implementation can refer to Github