All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0006_zigzag_conversion.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
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()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy