Given a string path, which is an absolute path (starting with a slash ‘/’) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period ‘.’ refers to the current directory, a double period ‘..’ refers to the directory up a level, and any multiple consecutive slashes (i.e., ‘//’) are treated as a single slash ‘/’. For this problem, any other format of periods such as ‘…’ are treated as file/directory names.
The canonical path should have the following format:
Return the simplified canonical path.
Input: path = “/home/” Output: “/home”
Input: path = “/../” Output: “/”
Input: path = “/home//foo/” Output: “/home/foo”
/
(like relative paths)?
import java.util.*;
public class SimplifyPath {
public String simplifyPath(String path) {
// Split the path by '/'
String[] components = path.split("/");
Stack<String> stack = new Stack<>();
for (String component : components) {
if (component.equals("") || component.equals(".")) {
// Skip empty and current directory components
continue;
}
if (component.equals("..")) {
// Move one directory up - Remove one directory if possible
if (!stack.isEmpty()) {
stack.pop();
}
} else {
// Add current directory name to the stack
stack.push(component);
}
}
// Reconstruct the canonical path
StringBuilder result = new StringBuilder();
for (String dir : stack) {
result.append("/").append(dir);
}
// Return the canonical path, return "/" if it's empty
return result.length() > 0 ? result.toString() : "/";
}
public static void main(String[] args) {
SimplifyPath simplifier = new SimplifyPath();
System.out.println(simplifier.simplifyPath("/home/")); // Output: "/home"
System.out.println(simplifier.simplifyPath("/../")); // Output: "/"
System.out.println(simplifier.simplifyPath("/home//foo/")); // Output: "/home/foo"
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?