Split path by '/' and use a stack. Push valid directory names, ignore empty strings and '.', pop from stack on '..', then join remaining names with '/'.
def simplifyPath(path: str) -> str:
stack = []
for part in path.split("/"):
if part == "..":
if stack:
stack.pop()
elif part and part != ".":
stack.append(part)
return "/" + "/".join(stack)
class Solution {
public String simplifyPath(String path) {
Deque stack = new LinkedList<>();
for (String part : path.split("/")) {
if (part.equals("..")) {
if (!stack.isEmpty()) stack.pop();
} else if (!part.isEmpty() && !part.equals(".")) {
stack.push(part);
}
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()) {
res.append("/").append(stack.pollLast());
}
return res.length() == 0 ? "/" : res.toString();
}
}