Repeat last occurrence of each alphanumeric character to their position in character family times | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void encodeString ( string str ) { string res = " " ; int small [ 26 ] = { 0 } , capital [ 26 ] = { 0 } , num [ 10 ] = { 0 } ; int n = str . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] >= '0' && str [ i ] <= '9' ) { num [ str [ i ] - 48 ] = i ; } else if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { small [ str [ i ] - 97 ] = i ; } else if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { capital [ str [ i ] - 65 ] = i ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) && small [ str [ i ] - 97 ] == i ) { int occ = str [ i ] - 96 ; while ( occ -- ) { res += str [ i ] ; } } else if ( ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) && capital [ str [ i ] - 65 ] == i ) { int occ = str [ i ] - 64 ; while ( occ -- ) { res += str [ i ] ; } } else if ( ( str [ i ] >= '0' && str [ i ] <= '9' ) && num [ str [ i ] - 48 ] == i ) { int occ = str [ i ] - 48 ; while ( occ -- ) { res += str [ i ] ; } } else { res += str [ i ] ; } } cout << res ; } int main ( ) { string str = " Ea2 , ▁ 0 , ▁ E " ; encodeString ( str ) ; return 0 ; }