LeetCode之Sorting the Sentence(Kotlin)

问题:



方法:
遍历字符串,将单词保存到map中,然后将map中单词按key值重新进行拼装即可。

import kotlin.text.StringBuilder

class SortingTheSentence {
    fun sortSentence(s: String): String {
        val sb = StringBuilder()
        val map = mutableMapOf()
        s.forEachIndexed { index, it ->
            if (it.isDigit()) {
                map[it.toString().toInt()] = sb.toString()
                sb.clear()
            } else if (!it.isWhitespace()) {
                sb.append(it)
            }
        }
        val result = StringBuilder()
        for (index in 1..map.size) {
            result.append(map[index])
            result.append(" ")
        }
        return result.trim().toString()
    }
}

fun main() {
    val input = "is2 sentence4 This1 a3"
    val sortingTheSentence = SortingTheSentence()
    sortingTheSentence.sortSentence(input)
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Sorting the Sentence(Kotlin))