Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.1 public class Solution { 2 public String simplifyPath(String path) { 3 int len = path.length(); 4 if(len<=0) return ""; 5 int i=0; 6 Stack<String> stack = new Stack<String> (); 7 while(i<len){ 8 while(i<len && path.charAt(i)=='/'){ 9 i++; 10 } 11 if(i==len)break; 12 int start = i; 13 while(i<len && path.charAt(i)!='/'){ 14 i++; 15 } 16 int end = i; 17 String cur = path.substring(start,end); 18 if(cur.equals("..") ){ 19 if( !stack.isEmpty()) //be carefull about here can't code like if(cur.equals("..") && !stack.isEmpty()) 20 stack.pop(); 21 } 22 else if(!cur.equals(".")){ 23 stack.push(cur); 24 } 25 } 26 if(stack.isEmpty()) return "/"; 27 StringBuilder sb = new StringBuilder(); 28 while(!stack.isEmpty()){ 29 30 sb.insert(0,stack.pop()); 31 sb.insert(0,'/'); 32 } 33 return sb.toString(); 34 } 35 }
// don't forget