Advertisement
thewitchking

Untitled

Jul 6th, 2025
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6.  
  7. string simplifyPath(const string& path) {
  8.     vector<string> stack;
  9.     stringstream ss(path);
  10.     string token;
  11.  
  12.     while (getline(ss, token, '/')) {
  13.         if (token == "" || token == ".") {
  14.             continue; // Ignore empty or current dir
  15.         } else if (token == "..") {
  16.             if (!stack.empty()) stack.pop_back(); // Go up a directory
  17.         } else {
  18.             stack.push_back(token); // Valid directory name
  19.         }
  20.     }
  21.  
  22.     string result;
  23.     for (const string& dir : stack) {
  24.         result += "/" + dir;
  25.     }
  26.  
  27.     return result.empty() ? "/" : result;
  28. }
  29.  
  30. void runTests() {
  31.     vector<pair<string, string>> tests = {
  32.         {"a/b/.././///c", "/a/c"},
  33.         {"/home/", "/home"},
  34.         {"/../", "/"},
  35.         {"/home//foo/", "/home/foo"},
  36.         {"/a/./b/../../c/", "/c"},
  37.         {"/a/../../b/../c//.//", "/c"},
  38.         {"/a//b////c/d//././/..", "/a/b/c"},
  39.         {"////", "/"},
  40.         {"", "/"},
  41.         {"../", "/"},
  42.         {"/...", "/..."},
  43.         {"/.hidden", "/.hidden"}
  44.     };
  45.  
  46.     for (auto& [input, expected] : tests) {
  47.         string result = simplifyPath(input);
  48.         cout << "Input: \"" << input << "\" | Output: \"" << result << "\" | Expected: \"" << expected << "\""
  49.              << (result == expected ? " ✅" : " ❌") << endl;
  50.     }
  51. }
  52.  
  53. int main() {
  54.     runTests();
  55.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement