Reverse the substrings of the given String according to the given Array of indices | Function to reverse a string ; Swap character starting from two corners ; Function to reverse the string with the given array of indices ; Reverse the string from 0 to A [ 0 ] ; Reverse the string for A [ i ] to A [ i + 1 ] ; Reverse String for A [ n - 1 ] to length ; Driver Code
function reverseStr ( str , l , h ) { var n = h - l ; for ( var i = 0 ; i < n / 2 ; i ++ ) { [ str [ i + l ] , str [ n - i - 1 + l ] ] = [ str [ n - i - 1 + l ] , str [ i + l ] ] ; } return str ; } function reverseString ( s , A , n ) { s = reverseStr ( s , 0 , A [ 0 ] ) ; for ( var i = 1 ; i < n ; i ++ ) s = reverseStr ( s , A [ i - 1 ] , A [ i ] ) ; s = reverseStr ( s , A [ n - 1 ] , s . length ) ; return s ; } var s = " " ; var A = [ 2 , 4 , 6 ] ; var n = A . length ; s = reverseString ( s . split ( ' ' ) , A , n ) ; document . write ( s . join ( ' ' ) ) ;