![JAR search and dependency download from the Maven repository](/logo.png)
g1101_1200.s1138_alphabet_board_path.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 g1101_1200.s1138_alphabet_board_path
// #Medium #String #Hash_Table #2023_05_31_Time_138_ms_(100.00%)_Space_34.8_MB_(100.00%)
class Solution {
fun alphabetBoardPath(target: String): String {
if (target.isEmpty()) {
return ""
}
var sourceRow = 0
var sourceCol = 0
val path = StringBuilder()
for (c in target.toCharArray()) {
val position = c.code - 97
val targetRow = position / 5
val targetCol = position % 5
if (targetCol < sourceCol) {
path.append(helper("L", sourceCol - targetCol))
}
if (targetRow < sourceRow) {
path.append(helper("U", sourceRow - targetRow))
}
if (targetRow > sourceRow) {
path.append(helper("D", targetRow - sourceRow))
}
if (targetCol > sourceCol) {
path.append(helper("R", targetCol - sourceCol))
}
path.append("!")
sourceRow = targetRow
sourceCol = targetCol
}
return path.toString()
}
fun helper(dir: String?, time: Int): StringBuilder {
val path = StringBuilder()
for (i in 0 until time) {
path.append(dir)
}
return path
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy