Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/"
, =>"/home"
path ="/a/./b/../../c/"
, =>"/c"
Corner Cases:
- 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"
.
算法思路:
栈。设置两指针,根据‘/’分割出一个一个的路径名,压栈。pop的时候,遇到‘.’和“”(//生产的)不用管,".."回滚,并记录回滚次数。
注意:当路径为空时,要返回 / 。
吐槽:有一个奇葩case -> /... 后来才反映过来,人家的路径名叫...搞笑吗?
1 public class Solution { 2 public String simplifyPath(String path) { 3 if(path == null || path.length() == 0) return ""; 4 int start = 0; 5 Stack<String> stack = new Stack<String>(); 6 for(int i = 1; i < path.length(); i++){ 7 if(path.charAt(i) == ‘/‘ || i == path.length() - 1){ 8 String s = (path.charAt(i) == ‘/‘) ? path.substring(start + 1, i) : path.substring(start + 1, i + 1); 9 stack.push(s); 10 start = i; 11 } 12 } 13 StringBuilder sb = new StringBuilder(); 14 int traceBack = 0; 15 while(!stack.isEmpty()){ 16 String str = stack.pop(); 17 if(".".equals(str) || str.length() == 0)continue; 18 else if("..".equals(str)) { 19 traceBack++; 20 }else{ 21 traceBack--; 22 if(traceBack < 0){ 23 sb.insert(0, "/" + str); 24 traceBack = 0; 25 } 26 } 27 } 28 return sb.toString().length() == 0 ? "/" : sb.toString(); 29 } 30 }
[leetcode]Simplify Path,布布扣,bubuko.com
原文:http://www.cnblogs.com/huntfor/p/3866612.html