LeetCode之Increasing Decreasing S

2021-05-27  本文已影响0人  糕冷羊

问题:



方法:
先把字母按顺序计数,然后正向反向遍历,如果数字不为0则结果中添加改字母,并减1,否则直接跳过,最后输出结果即可。

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"))
}

有问题随时沟通

具体代码实现可以参考Github

上一篇下一篇

猜你喜欢

热点阅读