Given an absolute path for a file (Unix-style), simplify it.
For example,
path?=?"/home/", =>?"/home"
path?=?"/a/./b/../../c/", =>?"/c"
?
public class Solution {
public String simplifyPath(String path) {
if (path==null || path.length()==0) {
return new String();
}
String[] arr = path.split("/");
Stack<String> stack = new Stack<String>();
for (int i=0; i<arr.length; i++) {
if (arr[i].equals("..")) {
if (stack.size() > 0) {
stack.pop();
} else {
continue;
}
} else if (arr[i].equals(".") || arr[i].length()==0) {
continue;
} else {
stack.push(arr[i]);
}
}
StringBuilder res = new StringBuilder();
if (stack.size()==0) {
return "/";
}
Stack<String> stack2 = new Stack<String>();
while (stack.size() > 0) {
stack2.push(stack.pop());
}
while (stack2.size() > 0) {
res.append("/");
res.append(stack2.pop());
}
return res.toString();
}
}
?
原文:http://hcx2013.iteye.com/blog/2222703