Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Solution:
public String simplifyPath(String path) {
LinkedList<String> list = new LinkedList<>();
Set<String> skip = new HashSet<>(Arrays.asList("..", ".", ""));
for (String dir : path.split("/")) {
if (dir.equals("..") && !list.isEmpty()) {
list.removeLast();
} else if (!skip.contains(dir)) {
list.add(dir);
}
}
String result = "";
for (String dir : list) {
result += "/" + dir;
}
return result.isEmpty() ? "/" : result;
}