g0001_0100.s0071_simplify_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 g0001_0100.s0071_simplify_path
// #Medium #String #Stack #2023_07_10_Time_185_ms_(92.86%)_Space_36.3_MB_(100.00%)
import java.util.ArrayDeque
import java.util.Deque
class Solution {
fun simplifyPath(path: String): String {
val stk: Deque = ArrayDeque()
var start = 0
while (start < path.length) {
while (start < path.length && path[start] == '/') {
start++
}
var end = start
while (end < path.length && path[end] != '/') {
end++
}
val s = path.substring(start, end)
if (s == "..") {
if (stk.isNotEmpty()) {
stk.pop()
}
} else if (s != "." && s != "") {
stk.push(s)
}
start = end + 1
}
val ans = StringBuilder()
while (stk.isNotEmpty()) {
ans.insert(0, stk.pop())
ans.insert(0, "/")
}
return if (ans.length > 0) ans.toString() else "/"
}
}