Largest string obtained in Dictionary order after deleting K characters | Java program for the above approach ; Function to find the largest string after deleting k characters ; Deque dq used to find the largest string in dictionary after deleting k characters ; Iterate till the length of the string ; Condition for popping characters from deque ; To store the resultant string ; To form resultant string ; Return the resultant string ; Driver Code ; Given String ; Function call ; Print the answer
import java . util . ArrayDeque ; import java . util . Deque ; import java . util . Scanner ; import java . io . IOException ; public class GFG { public static String largestString ( int n , int k , String sc ) { char [ ] s = sc . toCharArray ( ) ; Deque < Character > deq = new ArrayDeque < > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { while ( deq . size ( ) > 0 && deq . getLast ( ) < s [ i ] && k > 0 ) { deq . pollLast ( ) ; k -- ; } deq . add ( s [ i ] ) ; } String st = " " ; for ( char c : deq ) st = st + Character . toString ( c ) ; return st ; } public static void main ( String [ ] args ) throws IOException { int n = 4 ; int k = 2 ; String sc = " ritz " ; String result = largestString ( n , k , sc ) ; System . out . println ( result ) ; } }