LeetCode Entry
71. Simplify Path
split the string by /
71. Simplify Path medium
fun simplifyPath(path: String): String =
"/" + Stack<String>().apply {
path.split("/").forEach {
when (it) {
".." -> if (isNotEmpty()) pop()
"." -> Unit
"" -> Unit
else -> push(it)
}
}
}.joinToString("/")
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/178
Intuition
We can simulate what each of the . and .. commands do by using a Stack.
Approach
- split the string by
/ - add elements to the Stack if they are not commands and not empty
Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(n)\)