Lexicographically smallest string formed by appending a character from the first K characters of a given string | C ++ program to find the new string after performing deletions and append operation in the string s ; Function to find the new string thus formed by removing characters ; new string ; Remove characters until the string is empty ; Traverse to find the smallest character in the first k characters ; append the smallest character ; removing the lexicographically smallest character from the string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string newString ( string s , int k ) { string X = " " ; while ( s . length ( ) > 0 ) { char temp = s [ 0 ] ; for ( long long i = 1 ; i < k and i < s . length ( ) ; i ++ ) { if ( s [ i ] < temp ) { temp = s [ i ] ; } } X = X + temp ; for ( long long i = 0 ; i < k ; i ++ ) { if ( s [ i ] == temp ) { s . erase ( s . begin ( ) + i ) ; break ; } } } return X ; } int main ( ) { string s = " gaurang " ; int k = 3 ; cout << newString ( s , k ) ; }