Simplify the directory path ( Unix like ) | 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 ; absolute path which we have to simplify .
function simplify ( path ) { let v = [ ] ; let n = path . length ; let ans = " " ; for ( let i = 0 ; i < n ; i ++ ) { let dir = " " ; while ( i < n && path [ i ] != ' ' ) { dir += path [ i ] ; i ++ ; } if ( dir == " " ) { if ( v . length > 0 ) v . pop ( ) ; } else if ( dir == " " dir == " " ) { } else { v . push ( dir ) ; } } for ( let i of v ) { ans += " " + i ; } if ( ans == " " ) return " " ; return ans ; } let Str = " " ; let res = simplify ( Str ) ; document . write ( res ) ;