Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
We need to use a deque to store the path.
Then we only need to iterate the deque to get the result
public class Solution {
public String simplifyPath(String path) {
Deque<String> deque = new LinkedList<>();
String[] tokens = path.split("/");
for (String token: tokens) {
if (token.equals("..")) {
if (!deque.isEmpty()) {
deque.removeLast();
}
} else if (!token.equals(".") && !token.equals("")) {
deque.addLast(token);
}
}
StringBuilder sb = new StringBuilder();
while (!deque.isEmpty()) {
sb.append("/");
sb.append(deque.removeFirst());
}
return sb.length() > 0 ? sb.toString() : "/";
}
}