美文网首页
LeetCode之Sorting the Sentence(Ko

LeetCode之Sorting the Sentence(Ko

作者: 糕冷羊 | 来源:发表于2021-12-27 23:47 被阅读0次

问题:



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

import kotlin.text.StringBuilder

class SortingTheSentence {
    fun sortSentence(s: String): String {
        val sb = StringBuilder()
        val map = mutableMapOf<Int, String>()
        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(Ko

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