g0001_0100.s0006_zigzag_conversion.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0006_zigzag_conversion
// #Medium #String #2022_09_22_Time_366_ms_(80.62%)_Space_41.6_MB_(75.43%)
class Solution {
fun convert(s: String, numRows: Int): String {
val sLen = s.length
if (numRows == 1) {
return s
}
val maxDist = numRows * 2 - 2
val buf = StringBuilder()
for (i in 0 until numRows) {
var index = i
if (i == 0 || i == numRows - 1) {
while (index < sLen) {
buf.append(s[index])
index += maxDist
}
} else {
while (index < sLen) {
buf.append(s[index])
index += maxDist - i * 2
if (index >= sLen) {
break
}
buf.append(s[index])
index += i * 2
}
}
}
return buf.toString()
}
}