beats 95% - Java solution


  • 0
    N

    Idea is that I split the input based on "/" and build a string array with individual result and concatenate later.

    public String simplifyPath(String path) {
        
        if(path==null || path.length()==0) return "";
        String [] splits = path.split("/");
        int count=0, i=splits.length;
        int index = i-1;
        
        while(--i>=0){
            String cur = splits[i];
            if(cur.length()==0 || cur.equals(".")) continue;
            if(cur.equals("..")){
                count++;
            }else if(count>0){
                count--;
            }else{
                splits[index--] = cur;
            }
        }
        
        StringBuilder r = new StringBuilder();
        for(int j=index+1; j<splits.length; j++){
            r.append("/").append(splits[j]);
        }
        
        return r.length()==0?"/":r.toString();
    }

Log in to reply
 

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