Repeat last occurrence of each alphanumeric character to their position in character family times | Java program for the above approach ; Function to encode the given string ; Variable string to store the result ; Arrays to store the last occuring index of every character in the string ; Length of the string ; Iterate over the range ; If str [ i ] is between 0 and 9 ; If str [ i ] is between a and z ; If str [ i ] is between A and Z ; Iterate over the range ; If str [ i ] is between a and z and i is the last occurence in str ; If str [ i ] is between A and Z and i is the last occurence in str ; If str [ i ] is between 0 and 9 and i is the last occurence in str ; Print the result ; Driver Code
import java . io . * ; class GFG { static void encodeString ( String str ) { String res = " " ; int small [ ] = new int [ 26 ] ; int capital [ ] = new int [ 26 ] ; int num [ ] = new int [ 10 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { small [ i ] = 0 ; capital [ i ] = 0 ; } for ( int i = 0 ; i < 10 ; i ++ ) { num [ i ] = 0 ; } int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) >= '0' && str . charAt ( i ) <= '9' ) { num [ str . charAt ( i ) - 48 ] = i ; } else if ( str . charAt ( i ) >= ' a ' && str . charAt ( i ) <= ' z ' ) { small [ str . charAt ( i ) - 97 ] = i ; } else if ( str . charAt ( i ) >= ' A ' && str . charAt ( i ) <= ' Z ' ) { capital [ str . charAt ( i ) - 65 ] = i ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( ( str . charAt ( i ) >= ' a ' && str . charAt ( i ) <= ' z ' ) && small [ str . charAt ( i ) - 97 ] == i ) { int occ = str . charAt ( i ) - 96 ; while ( occ -- > 0 ) { res += str . charAt ( i ) ; } } else if ( ( str . charAt ( i ) >= ' A ' && str . charAt ( i ) <= ' Z ' ) && capital [ str . charAt ( i ) - 65 ] == i ) { int occ = str . charAt ( i ) - 64 ; while ( occ -- > 0 ) { res = res + str . charAt ( i ) ; } } else if ( ( str . charAt ( i ) >= '0' && str . charAt ( i ) <= '9' ) && num [ str . charAt ( i ) - 48 ] == i ) { int occ = str . charAt ( i ) - 48 ; while ( occ -- > 0 ) { res = res + str . charAt ( i ) ; } } else { res = res + str . charAt ( i ) ; } } System . out . print ( res ) ; } public static void main ( String [ ] args ) { String str = " Ea2 , ▁ 0 , ▁ E " ; encodeString ( str ) ; } }