2015年9月26日星期六

Leetcode 71 Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Solution 1: Use stack. One thing to be noticed is that, when use String split function, it may contains blank strings.
 public class Solution {  
   public String simplifyPath(String path) {  
     String[] strs=path.split("/"); //note: may have blank string  
     Deque<String> stack=new LinkedList<>();  
     for (String x:strs) {  
       if (x.equals("..")) {  
         if (!stack.isEmpty()) stack.pop();  
       }  
       else if (x.length()>0 && !x.equals(".")) stack.push(x); //  
     }  
     StringBuilder res=new StringBuilder();  
     while (!stack.isEmpty()) {  
       res.insert(0,stack.pop());  
       res.insert(0,'/');  
     }  
     if (res.length()==0) return "/";  
     return res.toString();  
   }  
 }  

没有评论:

发表评论