LeetCode Entry

71. Simplify Path

12.04.2023 medium 2023 kotlin

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("/")

blog post substack

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)\)