惯用的字符串分组(计算连续重复的字符)

Mil*_*ent 0 idioms kotlin

怎样用什么成语才能达到预期的效果呢?

val input = "aaaabbbcca"

val result = input.(here do the transformations)

val output = listOf("a" to 4, "b" to 3, "c" to 2, "a" to 1)

assert(result == output)
Run Code Online (Sandbox Code Playgroud)

Ada*_*hip 7

这是一种有趣的方法,可以使用fold

fun main() {
    val result = "aaaabbbcca"
        .chunked(1)
        .fold(emptyList<Pair<String, Int>>()) { list, current ->
            val (prev, count) = list.lastOrNull() ?: Pair(current, 0)
            if (prev == current) list.dropLast(1) + Pair(current, count + 1)
            else list + Pair(current, 1)
        }

    val output = listOf("a" to 4, "b" to 3, "c" to 2, "a" to 1)
    check(result == output)
    println(result)
}
Run Code Online (Sandbox Code Playgroud)

输出:

[(a, 4), (b, 3), (c, 2), (a, 1)]
Run Code Online (Sandbox Code Playgroud)