Reverse substrings of given string according to specified array indices | Java program for the above approach ; Function to perform the reversal operation on the given String ; Size of String ; Stores the count of indices ; Count the positions where reversals will begin ; Store the count of reversals beginning at position i ; Check if the count [ i ] is odd the swap the character ; Return the updated String ; Swap char of a string ; Driver Code ; Given String str ; Given array of reversing index ; Function Call
import java . util . * ; class GFG { static String modifyString ( int A [ ] , String str , int K ) { int N = str . length ( ) ; int count [ ] = new int [ N + 1 ] ; for ( int i = 0 ; i < K ; i ++ ) { count [ A [ i ] ] ++ ; } for ( int i = 1 ; i <= N / 2 ; i ++ ) { count [ i ] = count [ i ] + count [ i - 1 ] ; if ( ( count [ i ] & 1 ) > 0 ) { str = swap ( str , i - 1 , N - i ) ; } } return str ; } static String swap ( String str , int i , int j ) { char ch [ ] = str . toCharArray ( ) ; char temp = ch [ i ] ; ch [ i ] = ch [ j ] ; ch [ j ] = temp ; return String . valueOf ( ch ) ; } public static void main ( String [ ] args ) { String str = " abcdef " ; int arr [ ] = { 1 , 2 , 3 } ; int K = arr . length ; System . out . print ( modifyString ( arr , str , K ) ) ; } }