SHARE
TWEET

Untitled

a guest Oct 21st, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <string>
  3. #include <stack>
  4.  
  5. using namespace std;
  6.  
  7. void reverse_stack(stack<string>& stk) {
  8.     stack<string> rev;
  9.     while (stk.size() > 0) {
  10.         rev.push(stk.top());
  11.         stk.pop();
  12.     }
  13.     stk = rev;
  14. }
  15.  
  16. string simplifyPath(string path) {
  17.     stack<string> stk;
  18.     string dir;  //current directory name that we are compiling
  19.  
  20.     for (int i=0; i<path.size(); ++i) {
  21.         if (path[i] == '/' || i==path.size()-1) {
  22.             if (i==path.size()-1 && path[i]!='/') //last char exception
  23.                 dir += path[i];
  24.             if (dir == ".." && stk.size()>0) {
  25.                 stk.pop();
  26.                 dir = "";
  27.             }
  28.             else if (dir=="." || (stk.size()==0 && dir==".."))
  29.                 dir = "";
  30.             else if (dir != "") {
  31.                 stk.push(dir);
  32.                 dir = "";
  33.             }
  34.             //skip subsequent slashes
  35.             while (i+1<path.size() && path[i+1]=='/')
  36.                 i++;
  37.         }
  38.         else
  39.             dir += path[i];
  40.     }
  41.     //finally compose canonical path from stack
  42.     reverse_stack(stk);
  43.     string ret;
  44.     while (stk.size() > 0) {
  45.         ret += '/';
  46.         ret += stk.top();
  47.         stk.pop();
  48.     }
  49.     if (ret == "")
  50.         ret += "/";
  51.     return ret;
  52. }
  53.  
  54. int main() {
  55.     string path = "/..."; //"/home/"; //"/../"; //"/home//foo/"; //"/a/./b/../../c/"; //"/a/../../b/../c//.//"; //"/a//b////c/d//././/..";
  56.     cout << simplifyPath(path) << "\n";
  57.     return 0;
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top