Clean Java Solution using ArrayList


  • -1
    C
     public String simplifyPath(String path) {
            if(path==null || path.length()==0)
                return path;
            String[] paths = path.split("/");
            List<String> list = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            sb.append("/");
            for(int i=0; i<paths.length; i++){
                if(paths[i].equals(".") || paths[i].equals(""))
                    continue;
                else if(paths[i].equals("..")){
                    if(list.size()>0)
                        list.remove(list.size()-1);
                }else
                    list.add(paths[i]);
            }
            for(int i=0; i<list.size(); i++){
                sb.append(list.get(i));
                if(i<list.size()-1)
                    sb.append("/");
            }
            
            return sb.toString();
        }

Log in to reply
 

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