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 .
using System ; using System . Collections . Generic ; class GFG { static string simplify ( string path ) { List < string > v = new List < string > ( ) ; 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 . Count != 0 ) v . RemoveAt ( v . Count - 1 ) ; } else if ( dir == " . " dir == " " ) { } else { v . Add ( dir ) ; } } foreach ( string i in v ) { ans += " / " + i ; } if ( ans == " " ) return " / " ; return ans ; } static void Main ( ) { string str = " / a / . / b / . . / . . / c / " ; string res = simplify ( str ) ; Console . Write ( res ) ; } }