Simplify Path

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:

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

Tips:

建一个stack,以slash分,遇到.不管,遇到..pop。

The main idea is to push to the stack every valid file name (not in {"",".",".."}), popping only if there's smth to pop and we met "..". I don't feel like the code below needs any additional comments.

Code:

public class Solution {
    public String simplifyPath(String path) {
        StringBuilder sb = new StringBuilder("/");
        Stack<String> stack = new Stack<String>();
        for(String s: path.split("/")){
            if(s.equals("..")){
                if(!stack.isEmpty())
                    stack.pop();
            }
            else if(!s.equals("") && !s.equals("."))
                stack.push(s);
        }
        for(String s: stack){
            sb.append(s+"/");
        }
        if(!stack.isEmpty()) sb.setLength(sb.length()-1);
        return sb.toString();
    }
}

results matching ""

    No results matching ""