Kth character from the Nth string obtained by the given operations | Java program for the above approach ; String reverse ; Function to return Kth character from recursive String ; If N is 1 then return A ; Iterate a loop and generate the recursive String ; Update current String ; Change A to B and B to A ; Reverse the previous String ; Return the kth character ; Driver Code
import java . util . * ; class GFG { 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 ) ; } static char findKthChar ( int n , int k ) { String prev = " A " ; String cur = " " ; if ( n == 1 ) { return ' A ' ; } for ( int j = 2 ; j <= n ; j ++ ) { cur = prev + " B " ; for ( int i = 0 ; i < prev . length ( ) ; i ++ ) { if ( prev . charAt ( i ) == ' A ' ) { prev . replace ( prev . charAt ( i ) , ' B ' ) ; } else { prev . replace ( prev . charAt ( i ) , ' A ' ) ; } } prev = reverse ( prev ) ; cur += prev ; prev = cur ; } return cur . charAt ( k ) ; } public static void main ( String [ ] args ) { int N = 4 ; int K = 3 ; System . out . print ( findKthChar ( N , K ) ) ; } }