Java Solution without stack and split(), efficient!


  • 0
    J

    My ugly but efficient code without stack and build-in split(),using list and substring:

    public class Solution {
        public String simplifyPath(String path) {
            int st=0;
            int len=path.length();
            if(len==0||len==1) return path;
            List<String> list=new ArrayList<String>();
            StringBuffer sb=new StringBuffer();
            for(int i=1;i<=len;i++){ //i==len check the last substring
                if(i==len||path.charAt(i)=='/'){
                    String tmp=path.substring(st,i);
                    if("/..".equals(tmp)){ //backward a substring
                        if(list.size()!=0)
                            list.remove(list.size()-1);
                    }else if("/.".equals(tmp)||"/".equals(tmp)){     //"/" or "/." do nothing               
                    }else{
                        list.add(tmp);
                    }
                    st=i;
                }
            }
            if(list.size()==0) return "/";
    
            for(int i=0;i<list.size();i++){
                sb.append(list.get(i));
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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