Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- #include <vector>
- #include <string>
- using namespace std;
- string simplifyPath(const string& path) {
- vector<string> stack;
- stringstream ss(path);
- string token;
- while (getline(ss, token, '/')) {
- if (token == "" || token == ".") {
- continue; // Ignore empty or current dir
- } else if (token == "..") {
- if (!stack.empty()) stack.pop_back(); // Go up a directory
- } else {
- stack.push_back(token); // Valid directory name
- }
- }
- string result;
- for (const string& dir : stack) {
- result += "/" + dir;
- }
- return result.empty() ? "/" : result;
- }
- void runTests() {
- vector<pair<string, string>> tests = {
- {"a/b/.././///c", "/a/c"},
- {"/home/", "/home"},
- {"/../", "/"},
- {"/home//foo/", "/home/foo"},
- {"/a/./b/../../c/", "/c"},
- {"/a/../../b/../c//.//", "/c"},
- {"/a//b////c/d//././/..", "/a/b/c"},
- {"////", "/"},
- {"", "/"},
- {"../", "/"},
- {"/...", "/..."},
- {"/.hidden", "/.hidden"}
- };
- for (auto& [input, expected] : tests) {
- string result = simplifyPath(input);
- cout << "Input: \"" << input << "\" | Output: \"" << result << "\" | Expected: \"" << expected << "\""
- << (result == expected ? " ✅" : " ❌") << endl;
- }
- }
- int main() {
- runTests();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement