【题目】
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"
.
【解析】
用过Linux的人都应该熟悉这个,不过其中需要注意的是 /../ 的结果是 / ,也就是说根目录的上层目录还是根目录。
【Java代码】
public class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
int len = path.length();
int start = 0;
int i = 0;
while (i < len) {
while (i < len && path.charAt(i) == '/') {
i++;
}
start = i;
while (i < len && path.charAt(i) != '/') {
i++;
}
if (i > start) {
String part = path.substring(start, i);
if (part.equals("..")) {
if (!stack.isEmpty()) stack.pop();
} else if (!part.equals(".")) {
stack.push(part);
}
}
}
if (stack.isEmpty()) {
return "/";
}
String res = "";
while (!stack.isEmpty()) {
res = "/" + stack.pop() + res;
}
return res;
}
}