天天看點

Daily Coding Problem: Problem #713

import java.util.*

/**
This problem was asked by Quora.
Given an absolute pathname that may have . or .. as part of it, return the shortest standardized path.
For example, given "/usr/bin/../bin/./scripts/../", return "/usr/bin/".
 * */
class Problem_713 {
    /*
    * solution: Stack, Time:O(n), Space:O(n)
    * */
    fun simplifyPath(path: String): String {
        if (path == null || path.isEmpty()) {
            return ""
        }
        val list = path.split("/")
        val stack = Stack<String>()
        for (item in list) {
            if (item != "." && item != "..") {
                stack.push(item)
            } else if (stack.isNotEmpty() && item == "..") {
                stack.pop()
            }
        }
        return stack.joinToString("/")
    }
}