Remove Sub | Java program for the above approach ; Function to remove sub - directories from the given lists dir ; Store final result ; Sort the given directories ; Insert 1 st directory ; Iterating in directory ; Current directory ; Our previous valid directory ; Find length of previous directory ; If subdirectory is found ; Else store it in result valid directory ; Driver Code ; Given lists of directories dir [ ] ; Function Call
import java . io . * ; import java . util . * ; class GFG { static void eraseSubdirectory ( ArrayList < String > dir ) { ArrayList < String > res = new ArrayList < String > ( ) ; Collections . sort ( dir ) ; res . add ( dir . get ( 0 ) ) ; System . out . print ( " { " + dir . get ( 0 ) + " , ▁ " ) ; for ( int i = 1 ; i < dir . size ( ) ; i ++ ) { String curr = dir . get ( i ) ; String prev = res . get ( res . size ( ) - 1 ) ; int l = prev . length ( ) ; if ( curr . length ( ) > l && curr . charAt ( l ) == ' / ' && prev . equals ( curr . substring ( 0 , l ) ) ) continue ; res . add ( curr ) ; System . out . print ( curr + " , ▁ " ) ; } System . out . print ( "}NEW_LINE"); } public static void main ( String [ ] args ) { ArrayList < String > dir = new ArrayList < String > ( Arrays . asList ( " / a " , " / a / j " , " / c / d / e " , " / c / d " , " / b " ) ) ; eraseSubdirectory ( dir ) ; } }