Java 8 ms Straightforward Solution beats 92%


  • 0
    X
    public String simplifyPath(String path) {
        StringBuilder currDir = new StringBuilder();
        List<String> dir = new ArrayList<String>();
        path+='/';
        
        for(int i=0;i<path.length();i++){
            char c=path.charAt(i);
            if(c=='/'){
                if(currDir.length()==0){
                    continue;
                }else if(currDir.toString().equals(".")){
                }else if(currDir.toString().equals("..")){
                    if(!dir.isEmpty()) dir.remove(dir.size()-1);
                }else{
                    dir.add(currDir.toString());
                }
                currDir=new StringBuilder();
            }else currDir.append(c);
        }
        StringBuilder res = new StringBuilder();
        for(String lvldir:dir){
            res.append("/"+lvldir);
        }
        if(res.length()==0) return "/";
    
        return res.toString();
    }

Log in to reply
 

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