How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in Kotlin

1 Answer

0 votes
fun simplifyPath(path: String): String {
    val stack = mutableListOf<String>()  // Stack to hold valid directory names
    var result = ""                      // Final simplified path
    val psize = path.length              // Length of the input path
    var i = 0

    // Iterate through each character in the path
    while (i < psize) {
        if (path[i] == '/') {
            i++
            continue  // Skip redundant slashes
        }

        var pathpart = ""

        // Extract the next pathpart until the next slash
        while (i < psize && path[i] != '/') {
            pathpart += path[i]
            i++
        }

        // Ignore current directory references
        if (pathpart == ".") {
            continue
        }
        // Ignore parent directory references (no popping here)
        else if (pathpart == "..") {
            continue
        }
        // Valid directory name, push to stack
        else {
            stack.add(pathpart)
        }
    }

    // Reconstruct the simplified path from the stack
    while (stack.isNotEmpty()) {
        result = "/" + stack.removeAt(stack.lastIndex) + result
    }

    // If the stack was empty, return root directory
    return if (result.isNotEmpty()) result else "/"
}

fun main() {
    // Input path to be simplified
    val inputPath = "/home//foo/../bar/./unix/"

    val simplified = simplifyPath(inputPath)

    println("Simplified path: $simplified")
}



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 9, 2025 by avibootz
...