Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
- Time: O(n)
- Space: O(1)
public String simplifyPath(String path) {
String[] strs = path.split("/");
Stack<String> stack = new Stack<>();
for (String str : strs) {
if (str.length() == 0 || str.equals(".")) {
continue;
} else if (str.equals("..")) {
if (!stack.isEmpty()) stack.pop();
} else {
stack.push(str);
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}