Two points we should pay attention


  • 0

    This problem is simple. But I still learn two things from it.

    1. When we use split it can generate array containing empty String.
    2. When we iterate a stack the order is from bottom to top
    public String simplifyPath(String path) {
            if(path == null || path.length() == 0)
                return path;
                
            Stack<String> stack = new Stack<>();
            for(String p: path.split("/")){
                if(p.equals(".")){
                    continue;
                }else if(p.equals("..")){
                     if(!stack.isEmpty())
                        stack.pop();
                }else if(p.length()>0){
                    stack.push(p);
                }
            }
            
            String res = "";
            for(String p: stack){
                res = res + '/' + p;
            }
            
            return res.length()==0? "/": res;
        }
    
    

Log in to reply
 

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