K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void kThLexString ( string st , int k , int n ) { set < string > z ; for ( int i = 0 ; i < n ; i ++ ) { string pp ; for ( int j = i ; j < i + k ; j ++ ) { if ( j >= n ) break ; pp += st [ j ] ; z . insert ( pp ) ; } } vector < string > fin ( z . begin ( ) , z . end ( ) ) ; sort ( fin . begin ( ) , fin . end ( ) ) ; cout << fin [ k - 1 ] ; } int main ( ) { string s = " geeksforgeeks " ; int k = 5 ; int n = s . length ( ) ; kThLexString ( s , k , n ) ; }