71. Simplify Path

Link

Solution

這題透過stack紀錄所有的path,然後針對".." or "."進行處理

 public String simplifyPath(String path) {
        String[] tokens = path.split("/");
        Stack<String> s = new Stack();
        for(int i = 0; i < tokens.length; i++){
            if(tokens[i].equals("..")){
                if(!s.isEmpty()){
                    s.pop();
                }
            }
            else if(tokens[i].equals(".")){
                continue;
            }
            else{
                if(tokens[i].length() != 0) s.push(tokens[i]);
            }
        }
        String ret = "";
        while(!s.isEmpty()){
           ret = "/" + s.pop() + ret; 
        }
        if(ret.equals("")) return "/";
        else return ret;
    }

Last updated

Was this helpful?