Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
public class Solution {
public String simplifyPath(String path) {
if (path == null || path.length() < 1) {
return null;
}
String[] pathes = path.split("/");
Stack<String> stack = new Stack<String>();
for (String dir : pathes) {
if (dir.trim().length() < 1) {
continue;
}
if (dir.equals(".")) {
continue;
}
if (dir.trim().equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
continue;
}
stack.push(dir);
}
if (stack.isEmpty()) {
return "/";
}
String res = "";
while (!stack.isEmpty()) {
res = "/" + stack.pop() + res;
}
return res;
}
}