Simple Java solution


  • 0
    V
    public String simplifyPath(String path) {
            String[] dirs = path.split("/");
            Stack<String> stack = new Stack<>();
            for(String dir : dirs){
                if(!dir.equals("") && !dir.equals(".")){
                    if(dir.equals("..")){
                        if(!stack.isEmpty()) stack.pop();
                    } 
                    else stack.push(dir);
                }
            }
            StringBuilder sb = new StringBuilder();
            if(stack.isEmpty()) sb.insert(0, "/");
            while(!stack.isEmpty()){
                sb.insert(0, "/" + stack.pop());
            }
            return sb.toString();
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.