Simplify the directory path ( Unix like ) | C ++ implementation of optimized Approach 1 ; function to simplify a Unix - styled absolute path ; using vector in place of stack ; forming the current directory . ; if " . . " , we pop . ; do nothing ( added for better understanding . ) ; push the current directory into the vector . ; forming the ans ; vector is empty ; Driver Code ; absolute path which we have to simplify .
#include <bits/stdc++.h> NEW_LINE using namespace std ; string simplify ( string path ) { vector < string > v ; int n = path . length ( ) ; string ans ; for ( int i = 0 ; i < n ; i ++ ) { string dir = " " ; while ( i < n && path [ i ] != ' / ' ) { dir += path [ i ] ; i ++ ; } if ( dir == " . . " ) { if ( ! v . empty ( ) ) v . pop_back ( ) ; } else if ( dir == " . " dir == " " ) { } else { v . push_back ( dir ) ; } } for ( auto i : v ) { ans += " / " + i ; } if ( ans == " " ) return " / " ; return ans ; } int main ( ) { string str ( " / a / . / b / . . / . . / c / " ) ; string res = simplify ( str ) ; cout << res ; return 0 ; }