美文网首页
LeetCode之Increasing Decreasing S

LeetCode之Increasing Decreasing S

作者: 糕冷羊 | 来源:发表于2021-05-27 15:06 被阅读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

    相关文章

      网友评论

          本文标题:LeetCode之Increasing Decreasing S

          本文链接:https://www.haomeiwen.com/subject/iexdsltx.html