Kotlin:游程长度编码 [英] Kotlin: Run length encoding
本文介绍了Kotlin:游程长度编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
程序正常运行,但是,我仍然遇到逻辑错误:最后一个字母没有通过.例如,当我输入aaaabbbbccccdddd时,我得到的输出是a4b4c4,但没有d4.
The program works, however, I still get a logical error: the final letter doesn't run through. For example, when I enter aaaabbbbccccdddd the output I get is a4b4c4 but there is no 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
包含按从 0
到 iLength-1
的索引的字符您必须写 for(i in 0,直到iLength)
,而不是 for(i in 0..iLength)
strUser
contains chars by indexes from 0
to iLength - 1
so you have to write for (i in 0 until iLength)
instead of for (i in 0..iLength)
但是Tenfour04是完全正确的,您可以不带索引地迭代 strUser
:
But Tenfour04 is completely right, you can just iterate strUser
without indexes:
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
}
}
}
这篇关于Kotlin:游程长度编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文