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

For example,
path="/home/", =>"/home"
path="/a/./b/../../c/", =>"/c"

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

Solution: stack, .表示该directory,忽略;..表示上一directory,弹出stack

    public String simplifyPath(String path) {
        if(path == null || path.length() == 0){
            return "";
        }
        String[] parts = path.trim().split("/");
        Deque<String> stack = new LinkedList<>();
        for(String part : parts) {
            if(part == null || part.length() == 0 || part.equals(".")){
                continue;
            }
            if(part.equals("..")){
                if(!stack.isEmpty()){
                    stack.pollLast();
                }
                continue;
            }
            stack.offerLast(part);
        }
        StringBuilder sb = new StringBuilder();
        if(stack.isEmpty()){
            return "/";
        }
        while(!stack.isEmpty()){
            sb.append('/').append(stack.pollFirst());
        }
        return sb.toString();
    }

results matching ""

    No results matching ""