1+ #include < iostream>
2+ #include < string>
3+ #include < sstream>
4+ #include < vector>
5+ using namespace std ;
6+
7+ stringsimplifyPath (string path){
8+ // 1. Step - Tokenisation & Filtering
9+
10+ istringstreamiss (path);
11+ vector<string> tokens;
12+
13+ string token;
14+ while (getline (iss,token,' /' )){
15+ if (token==" ." or token==" " ){
16+ continue ;
17+ }
18+ tokens.push_back (token);
19+ }
20+
21+
22+ // 2. Handle ..
23+ vector<string> stack;
24+
25+ if (path[0 ]==' /' ){
26+ // denotes that our path is an abs path (wrt root dir)
27+ stack.push_back (" " );
28+ }
29+
30+ for (string token : tokens){
31+ if (token==" .." ){
32+ // 2 cases -> Abs path or relative path
33+ if (stack.size ()==0 or stack[stack.size ()-1 ]==" .." ){
34+ stack.push_back (" .." );
35+ }
36+
37+ else if (stack[stack.size ()-1 ]!=" " ){
38+ stack.pop_back ();
39+ }
40+ }
41+ else {
42+ // x,y,z...
43+ stack.push_back (token);
44+ }
45+
46+ }
47+ // single element
48+ if (stack.size ()==1 and stack[0 ]==" " ){
49+ return " /" ;
50+ }
51+
52+ // combine all elements in stack to get the answer
53+ ostringstream oss;
54+ int i =0 ;
55+
56+ for (auto token :stack){
57+ if (i!=0 ){
58+ oss<<" /" ;
59+ }
60+ i++;
61+ oss << token;
62+ }
63+
64+ return oss.str ();
65+
66+ }
67+
68+
69+ int main (){
70+ string path =" /../x/y/../z/././w/a///../../c/./" ;
71+ // Output : /x/z/c
72+ cout <<simplifyPath (path) <<endl;
73+
74+
75+
76+ return 0 ;
77+ }