Reverse substrings of given string according to specified array indices | C ++ 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 ; Driver Code ; Given string str ; Given array of reversing index ; Function Call
#include <iostream> NEW_LINE using namespace std ; string modifyString ( int A [ ] , string str , int K ) { int N = str . size ( ) ; int count [ N + 1 ] = { 0 } ; 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 ) { swap ( str [ i - 1 ] , str [ N - i ] ) ; } } return str ; } int main ( ) { string str = " abcdef " ; int arr [ ] = { 1 , 2 , 3 } ; int K = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << modifyString ( arr , str , K ) ; return 0 ; }