K | Java implementation of the above approach ; Set to store the unique substring ; String to create each substring ; Adding to set ; Converting set into a list ; Sorting the strings int the list into lexicographical order ; Printing kth substring ; Driver Code
import java . util . * ; class GFG { public static void kThLexString ( String st , int k , int n ) { Set < String > z = new HashSet < String > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { String pp = " " ; for ( int j = i ; j < i + k ; j ++ ) { if ( j >= n ) break ; pp += st . charAt ( j ) ; z . add ( pp ) ; } } Vector < String > fin = new Vector < String > ( ) ; fin . addAll ( z ) ; Collections . sort ( fin ) ; System . out . print ( fin . get ( k - 1 ) ) ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int k = 5 ; int n = s . length ( ) ; kThLexString ( s , k , n ) ; } }