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

 

posted @ 2020-11-14 10:01  johnny_zhao  阅读(63)  评论(0编辑  收藏  举报