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 ‘/’. The canonical path should have the following format:
Return the simplified canonical path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
#include <iostream>
#include <sstream>
#include <vector>
#include <stack>
std::string simplifyPath(std::string path) {
std::stack<std::string> st;
std::istringstream ss(path);
std::string token;
while (std::getline(ss, token, '/')) {
if (token == "..") {
if (!st.empty()) {
st.pop();
}
} else if (!token.empty() && token != ".") {
st.push(token);
}
}
std::string simplifiedPath;
while (!st.empty()) {
simplifiedPath = "/" + st.top() + simplifiedPath;
st.pop();
}
return simplifiedPath.empty() ? "/" : simplifiedPath;
}
int main() {
// Test cases
std::vector<std::string> testCases = {"/home/", "/../", "/home//foo/"};
for (const auto &path : testCases) {
std::cout << "Input: " << path << "\nOutput: " << simplifyPath(path) << "\n\n";
}
return 0;
}
The time complexity of this solution is O(n), where n is the length of the input string. This is because we process each character in the path string exactly once.
The space complexity is O(n) as well, for storing the split parts and for the stack, both of which in the worst case can contain all the directory names in the path.
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?