Make the string in AP by changing a character | C ++ program for the above problem ; Function to modify the given string and find the index where modification is needed ; Array to store the ASCII values of alphabets ; loop to compute the ASCII values of characters a - z ; Set to store all the possible differences between consecutive elements ; Loop to find out the differences between consecutive elements and storing them in the set ; Checks if any character of the string disobeys the pattern ; Constructing the strings with all possible values of consecutive difference and comparing them with staring string S . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void string_modify ( string s ) { char alphabets [ 26 ] ; int flag = 0 , hold_i ; char hold_l ; int i ; for ( i = 0 ; i < 26 ; i ++ ) { alphabets [ i ] = i + ' a ' ; } set < int > difference ; string reconstruct = " " ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { difference . insert ( s [ i ] - s [ i - 1 ] ) ; } if ( difference . size ( ) == 1 ) { cout << " No ▁ modifications ▁ required " ; return ; } for ( auto it = difference . begin ( ) ; it != difference . end ( ) ; it ++ ) { int index = s [ 0 ] - ' a ' ; reconstruct = " " ; flag = 0 ; for ( int i = 0 ; i < s . size ( ) && flag <= 1 ; i ++ ) { reconstruct += alphabets [ index ] ; index += * it ; if ( index < 0 ) { index += 26 ; } index %= 26 ; if ( reconstruct [ i ] != s [ i ] ) { flag ++ ; hold_i = i ; hold_l = s [ i ] ; } } if ( flag == 1 ) { s [ hold_i ] = reconstruct [ hold_i ] ; break ; } } if ( flag > 1 ) { hold_i = 0 ; hold_l = s [ 0 ] ; int temp = ( s [ 1 ] - ' a ' - ( s [ 2 ] - s [ 1 ] ) ) % 26 ; if ( temp < 0 ) { temp += 26 ; } s [ 0 ] = alphabets [ temp ] ; } cout << hold_i << " ▁ - > ▁ " << hold_l << endl << s << endl ; } int main ( ) { string s = " aeimqux " ; string_modify ( s ) ; }