Question:
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”.
Thinking:
The file system is like a tree, and finding path of this tree is like a dfs process. So we can use stack to track the node of dfs. If the string is “..”, we go back, otherwise go to the given dirctory.
Solution:
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] paths = path.split("/");
for (String p: paths) {
p = p.trim();
if (p.equals("") || p.equals(".")) continue;
if (p.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
continue;
}
stack.push(p);
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty())
res.insert(0, "/".concat(stack.pop()));
return res.length() == 0? "/":res.toString();
}