Java solution, using stack


  • 0
    M
    public class Solution {
        public String simplifyPath(String path) {
            if(path==null || path.length()==0 || path.equals("/")) return path;
            String[] folders = path.split("/");
            Stack<String> stack = new Stack<>();
            for(String folder : folders){
                if(folder.length()==0){
                    continue;
                } else if(folder.charAt(0)=='.' ){
                    if(folder.length()>2 && folder.length()>stack.size()+1) {
                        stack.push(folder);
                    } else {
                        for(int i=1; !stack.isEmpty() && i<folder.length(); i++) {
                            stack.pop();
                        }
                    }
                } else {
                    stack.push(folder);
                }
            }
            StringBuilder sb = new StringBuilder();
            for(String folder : stack) {
                sb.append("/"+folder);
            }
            if(sb.length()==0) return "/";
            return sb.toString();
        }
    }
    

    If you cannot understand "/..." , try to create a folder named ..., it would work. So "..." may be a folder's name, may be back to upper upper folder.


  • 0
    B

    @MadDetective said in Java solution, using stack:

    folder.length()>stack.size()+1

    I don't understand why do we need this condition. The code works even without this.


Log in to reply
 

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