Longest suffix such that occurrence of each character is less than N after deleting atmost K characters | Java implementation to find longest suffix of the String such that occurrence of each character is less than K ; Function to find the maximum length suffix in the String ; Length of the String ; Map to store the number of occurrence of character ; Loop to iterate String from the last character ; Condition to check if the occurrence of each character is less than given number ; Condition when character cannot be deleted ; Longest suffix ; Driver Code ; Function call
class GFG { static void maximumSuffix ( String s , int n , int k ) { int i = s . length ( ) - 1 ; int arr [ ] = new int [ 26 ] ; String suffix = " " ; while ( i > - 1 ) { int index = s . charAt ( i ) - ' a ' ; if ( arr [ index ] < n ) { arr [ index ] ++ ; suffix += s . charAt ( i ) ; i -- ; continue ; } if ( k == 0 ) break ; k -- ; i -- ; } suffix = reverse ( suffix ) ; System . out . print ( suffix ) ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String str = " iahagafedcba " ; int n = 1 , k = 2 ; maximumSuffix ( str , n , k ) ; } }