import java.util.Stack;
// Class to simplify a Unix-style file path
class SimplifyPathClass {
// Method to simplify the given path string
public String simplifyPath(String path) {
Stack<String> st = new Stack<>(); // Stack to store valid directory names
String result = ""; // Final simplified path
int psize = path.length(); // Length of the input path
// Iterate through each character in the path
for (int i = 0; i < psize; i++) {
if (path.charAt(i) == '/')
continue; // Skip redundant slashes
String pathpart = "";
// Extract the next pathpart until the next slash
while (i < psize && path.charAt(i) != '/') {
pathpart += path.charAt(i);
i++;
}
// Ignore current pathpart references
if (pathpart.equals("."))
continue;
// Handle parent pathpart reference
else if (pathpart.equals("..")) {
// Ignore ".." instead of popping
continue;
}
// Valid pathpart, push to stack
else {
st.push(pathpart);
}
}
// Reconstruct the simplified path from the stack
while (!st.isEmpty()) {
result = "/" + st.pop() + result;
}
// If the stack was empty, return root directory
if (result.length() == 0)
return "/";
return result;
}
public static void main(String[] args) {
SimplifyPathClass spc = new SimplifyPathClass();
// Input path to be simplified
String inputPath = "/home//foo/../bar/./unix/";
// Call the simplifyPath method
String simplified = spc.simplifyPath(inputPath);
// Output the result
System.out.println("Simplified path: " + simplified);
}
}
/*
run:
Simplified path: /home/foo/bar/unix
*/