Program to find the kth character after decrypting a string | Java implementation of the approach ; Function to print kth character of String s after decrypting it ; Get the length of string ; Initialise pointer to character of input string to zero ; Total length of resultant string ; Traverse the string from starting and check if each character is alphabet then increment total_len ; If total_leg equal to k then return string else increment i ; Parse the number ; Update next_total_len ; Get the position of kth character ; Position not found then update position with total_len ; Recursively find the kth position ; Else update total_len by next_total_len ; Return - 1 if character not found ; Driver code
import java . util . * ; class GfG { static Character findKthChar ( String s , int k ) { int len = s . length ( ) ; int i = 0 ; int total_len = 0 ; while ( i < len ) { if ( Character . isLetter ( s . charAt ( i ) ) ) { total_len ++ ; if ( total_len == k ) return s . charAt ( i ) ; i ++ ; } else { int n = 0 ; while ( i < len && ! Character . isLetter ( s . charAt ( i ) ) ) { n = n * 10 + ( s . charAt ( i ) - '0' ) ; i ++ ; } int next_total_len = total_len * n ; if ( k <= next_total_len ) { int pos = k % total_len ; if ( pos == 0 ) { pos = total_len ; } return findKthChar ( s , pos ) ; } else { total_len = next_total_len ; } } } return ' ▁ ' ; } public static void main ( String [ ] args ) { String s = " ab2c3" ; int k = 5 ; System . out . println ( findKthChar ( s , k ) ) ; } }