Kotlin: 运行 长度编码

Kotlin: Run length encoding

程序有效,但是,我仍然遇到逻辑错误:最后一个字母没有 运行 通过。例如,当我输入 aaaabbbbbccccdddd 时,我得到的输出是 a4b4c4 但没有 d4.

fun main () {

    val strUser = readLine()!!.toLowerCase()
    val iLength = strUser!!.length
    var iMatch : Int = 0
    var chrMatch : Char = strUser[0]

    for (i in 0..iLength) {

        if (strUser[i] == chrMatch) {

            iMatch += 1
        }else {
            print("$chrMatch$iMatch")
            chrMatch = strUser[i]
            iMatch = 1

        }


    }


}

strUser 包含索引从 0iLength - 1 的字符,因此您必须编写 for (i in 0 until iLength) 而不是 for (i in 0..iLength)

但是 Tenfour04 是完全正确的,你可以在没有索引的情况下迭代 strUser:

fun main() {
    val strUser = readLine()!!.toLowerCase()
    var iMatch: Int = 0
    var chrMatch: Char = strUser[0]

    for (char in strUser) {
        if (char == chrMatch) {
            iMatch += 1
        } else {
            print("$chrMatch$iMatch")
            chrMatch = char
            iMatch = 1
        }
    }
}

有趣的主要(){

val strUser = readLine()!!.toLowerCase()
var iMatch : Int = 0
var chrMatch : Char = strUser[0]

for (char in strUser+1) {

    if (char == chrMatch) {

        iMatch += 1
    }else {
        print("$chrMatch$iMatch")
        chrMatch = char
        iMatch = 1

    }


}

}

解法有很多,但最好的是RegExp

fun encode(input: String): String =
    input.replace(Regex("(.)\1*")) {
        String.format("%d%s", it.value.length, it.groupValues[1])
    }

demo

测试结果

println(encode("aaaabbbbccccdddd")) // 4a4b4c4d
fun runLengthEncoding(inputString: String): String {
        val n=inputString.length
        var i : Int =0
        var result : String =""
        while(i<n){
            var count =1
            while(i<n-1 && inputString[i] == inputString[i+1]){
                count ++
                i++
            }

            result=result.toString()+count.toString()+inputString[i].toString()
            i++
        }
        return result
    }