71. Simplify Path

題目:
Given an absolute path for a file (Unix-style), simplify it.java

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.ide

Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".this

解答:
unix style path的規則以下:
/ -> root
/a -> in (a)
. -> THIS dir path
/a/./ -> still in /a
/a/./b -> in /a/b
.. -> go "up" one level
/a/./b/.. -> /a/b/.. -> /a
/a/./b/../.. -> /a/.. -> /
/a/./b/../../c -> /cunix

public class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<String>();
        //三種須要跳過的狀況
        Set<String> skip = new HashSet<String>(Arrays.asList("..", ".", ""));
        
        for (String dir : path.split("/")) {
            //當遇到..時,須要向前進
            if (dir.equals("..") && !stack.isEmpty()) {
                stack.pop();
            } else if (!skip.contains(dir)) {
                stack.push(dir);
            }
        }
        String result = "";
        if (stack.isEmpty()) result += "/";
        while (!stack.isEmpty()) {
            //pop出來的順序是反的,因此加的時候,把最新pop出來的路徑加在前面
            result = "/" + stack.pop() + result;
        }
        return result;
    }
}
相關文章
相關標籤/搜索