Repeat last occurrence of each alphanumeric character to their position in character family times | 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
function encodeString ( str ) { let res = " " ; let small = new Array ( 26 ) . fill ( 0 ) , capital = new Array ( 26 ) . fill ( 0 ) , num = new Array ( 26 ) . fill ( 0 ) ; let n = str . length ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && str [ i ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) { num [ str [ i ] . charCodeAt ( 0 ) - 48 ] = i ; } else if ( str [ i ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && str [ i ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) { small [ str [ i ] . charCodeAt ( 0 ) - 97 ] = i ; } else if ( str [ i ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && str [ i ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) { capital [ str [ i ] . charCodeAt ( 0 ) - 65 ] = i ; } } for ( let i = 0 ; i < n ; i ++ ) { if ( ( str [ i ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && str [ i ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) && small [ str [ i ] . charCodeAt ( 0 ) - 97 ] == i ) { let occ = str [ i ] . charCodeAt ( 0 ) - 96 ; while ( occ -- ) { res += str [ i ] ; } } else if ( ( str [ i ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && str [ i ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) && capital [ str [ i ] . charCodeAt ( 0 ) - 65 ] == i ) { let occ = str [ i ] . charCodeAt ( 0 ) - 64 ; while ( occ -- ) { res += str [ i ] ; } } else if ( ( str [ i ] . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && str [ i ] . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) && num [ str [ i ] . charCodeAt ( 0 ) - 48 ] == i ) { let occ = str [ i ] . charCodeAt ( 0 ) - 48 ; while ( occ -- ) { res += str [ i ] ; } } else { res += str [ i ] ; } } document . write ( res ) ; } let str = " " ; encodeString ( str ) ;