Leetcode 71 Simplify Path
Approach
The idea is to get rid of unnecessary tokens from the path. Three types of tokens can be cleaned.
The empty token "//" --> "/".
"." token: /a/./b" -> "/a/b"
".." token : "/a/../b" -> "b".
Algorithm
Split the path into tokens separated by the "/" character.
Keep track of subdirectories in a stack data structure.
If a token is neither "." nor "..", it could be part of the simplified path, so push it onto the stack. If the token is "..", remove the top subdirectory from the stack if it is non-empty. Ignore "." tokens.
Join the subdirectories present in the stack with the "/" character to form the simplified path.
public String simplifyPath(String path) {
String DELIMITER = "/";
var tokens = path.split(DELIMITER);
var stack = new Stack<String>();
for (var token : tokens) {
if (token.length() != 0) {
if (!token.equals(".") && !token.equals(".."))
stack.push(token);
else if (token.equals("..") && !stack.empty())
stack.pop();
}
}
return DELIMITER + String.join(DELIMITER , stack);
}
