jayati

Simplify Path

Apr 12th, 2023
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string simplifyPath(string path) {
  4.     vector<string>   nameVect;
  5.     string name;
  6.    
  7.     path.push_back('/');
  8.     for(int i=0;i<path.size();i++){
  9.         if(path[i]=='/'){
  10.             if(name.size()==0)continue;
  11.             if(name==".."){     //special case 1:double dot,pop dir
  12.                  if(nameVect.size()>0)nameVect.pop_back();
  13.             }else if(name=="."){//special case 2:singel dot,don`t push
  14.             }else{         
  15.                 nameVect.push_back(name);
  16.             }
  17.             name.clear();
  18.         }else{
  19.             name.push_back(path[i]);//record the name
  20.         }
  21.     }
  22.  
  23.     string result;
  24.     if(nameVect.empty())return "/";
  25.     for(int i=0;i<nameVect.size();i++){
  26.         result.append("/"+nameVect[i]);
  27.     }
  28.     return result;
  29. }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment