Thursday, May 25, 2017

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"

 public String simplifyPath(String path) {  
     if(path==null || path.length()<=1) return path;  
     if(path.charAt(0)!='/') return "";  
     int last=1;  
     Deque st = new LinkedList<String>();  
     for(int i=1;i<=path.length();i++){  
       if(i==path.length() || path.charAt(i)=='/'){  
         String s=path.substring(last,i);  
         if(s.equals(".") || s.equals("")){  
         }  
         else if(s.equals("..")){  
           if(st.size()!=0) st.pop();  
         }  
         else {  
           st.push(s);  
         }  
         last=i+1;  
       }  
     }  
     if(st.size()==0) return "/";  
     StringBuilder sb=new StringBuilder();  
     while(st.size()!=0){  
       sb.append('/');  
       sb.append(st.removeLast());  
     }  
     return sb.toString();  
   }  

No comments:

Post a Comment