Java easy understanding solution which beat 85%, by Chaoyang He


  • 0

    the explanation of the code below:
    Firstly, use one loop to get all the path internals and save them to the Stack . For examples, if the input string is "/a/./b//../../c/", the first loop output will be:

    pathInternal =/a
    pathInternal =/.
    pathInternal =/b
    pathInternal =/
    pathInternal =/..
    pathInternal =/..
    pathInternal =/c
    pathInternal =/
    

    Secondly, when you get the path internals above, then filter some cases:
    if "/..", means the path should back one internal, so you should back one internal. But Do NOT back intermediately because before the "/.." there may be some ignore internals like "/." and "/", so just count the numbers of "/..", and back at the last "if else" branch.

    At the last, don't forget the result string(ret) may be empty, which means the path is equal "/".

    public class Solution {
        public String simplifyPath(String path) {
            if(path.isEmpty()) return "";
            Stack<String> stk = new Stack<>();
            int pathInternalBegin = 0, pathInternalEnd = 0;
            int i = 0;
            while(i < path.length() ){
                if(path.charAt(i) == '/') {
                    pathInternalBegin = i;
                    pathInternalEnd = pathInternalBegin;
                    i++;
                }
                while(i < path.length() && path.charAt(i) != '/') {
                    pathInternalEnd++;
                    i++;
                }
                String pathInternal = path.substring(pathInternalBegin, pathInternalEnd+1);
                stk.push(pathInternal);
                //System.out.println("pathInternal =" + pathInternal);
            }
            String ret = new String();
            int backcnt = 0;
            while(!stk.isEmpty()){
                String pathInternal = stk.pop();
                if(pathInternal.equals("/..")){
                    backcnt++;
                }else if(pathInternal.equals("/.")){
                    continue;
                }else if(pathInternal.equals("/")){
                    continue;
                }else if(backcnt > 0){
                    backcnt--;
                }else{
                    ret = pathInternal + ret;
                }
            }
            return ret.isEmpty() ? "/" : ret;
        }
    }
    

Log in to reply
 

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