71. Simplify Path

NO IMAGE

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

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

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”.

解答:
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 -> /c

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;
    }
}