標籤:style blog http color os strong io art
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.
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 }