Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

71. Simplify Path

Topics: String Stack

Solution

Implementation

class Solution {
    fun simplifyPath(path: String): String {
        val folders = path.split("/")
        val stack = mutableListOf<String>()

        for (folder in folders) {
            if (folder == "..") {
                stack.removeLastOrNull()
            } else if (folder != "" && folder != ".") {
                stack.add(folder)
            }
        }

        return stack.joinToString(prefix = "/", separator = "/")
    }
}