Simplify the directory path ( Unix like ) | Java 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 .
import java . util . * ; public class Main { static String simplify ( String path ) { Vector < String > v = new Vector < String > ( ) ; int n = path . length ( ) ; String ans = " " ; for ( int i = 0 ; i < n ; i ++ ) { String dir = " " ; while ( i < n && path . charAt ( i ) != ' / ' ) { dir += path . charAt ( i ) ; i ++ ; } if ( dir . equals ( " . . " ) ) { if ( v . size ( ) != 0 ) { v . remove ( v . size ( ) - 1 ) ; } } else if ( dir . equals ( " . " ) || dir . equals ( " " ) ) { } else { v . add ( dir ) ; } } for ( String i : v ) { ans += " / " + i ; } if ( ans == " " ) return " / " ; return ans ; } public static void main ( String [ ] args ) { String str = " / a / . / b / . . / . . / c / " ; String res = simplify ( str ) ; System . out . print ( res ) ; } }