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".
这道题主要考察对各种case的考虑,具体实现上就是字符串的处理,另外就是最后的reverse有点麻烦。
public String simplifyPath(String path) {
//special case
if (path.length() == 0) return "";
if (path.length() == 1) return "/";
//general case
Stack<String> stack = new Stack<>();
String[] strings = path.split("/");
for (int i = 0; i < strings.length; i++) {
String str = strings[i];
if (str.equals(".") || str.equals("")) {
continue;
} else if (str.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else {
stack.push(str);
}
}
if (stack.isEmpty()) return "/";
String res = "";
while (!stack.isEmpty()) {
res = "/" + stack.pop() + res;
}
return res;
}