71 Simplify Path
71. Simplify Path
1. Question
2. Implementation
class Solution {
public String simplifyPath(String path) {
Set<String> set = new HashSet<>();
set.add(".");
set.add("..");
set.add("");
Stack<String> stack = new Stack<>();
for (String dir : path.split("/")) {
if (dir.equals("..") && !stack.isEmpty()) {
stack.pop();
}
else if (!set.contains(dir)) {
stack.push(dir);
}
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()) {
res.insert(0, stack.pop());
res.insert(0, "/");
}
return res.length() == 0 ? "/" : res.toString();
}
}3. Time & Space Complexity
Last updated