Make the string in AP by changing a character | Java 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
import java . util . * ; class GFG { static void string_modify ( char [ ] s ) { char [ ] alphabets = new char [ 26 ] ; int flag = 0 , hold_i = 0 ; char hold_l = 0 ; int i ; for ( i = 0 ; i < 26 ; i ++ ) { alphabets [ i ] = ( char ) ( i + ' a ' ) ; } HashSet < Integer > difference = new HashSet < Integer > ( ) ; String reconstruct = " " ; for ( i = 1 ; i < s . length ; i ++ ) { difference . add ( s [ i ] - s [ i - 1 ] ) ; } if ( difference . size ( ) == 1 ) { System . out . print ( " No ▁ modifications ▁ required " ) ; return ; } for ( int it : difference ) { int index = s [ 0 ] - ' a ' ; reconstruct = " " ; flag = 0 ; for ( i = 0 ; i < s . length && flag <= 1 ; i ++ ) { reconstruct += alphabets [ index ] ; index += it ; if ( index < 0 ) { index += 26 ; } index %= 26 ; if ( reconstruct . charAt ( i ) != s [ i ] ) { flag ++ ; hold_i = i ; hold_l = s [ i ] ; } } if ( flag == 1 ) { s [ hold_i ] = reconstruct . charAt ( 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 ] ; } System . out . print ( hold_i + " ▁ - > ▁ " + hold_l + "NEW_LINE" + String . valueOf ( s ) + "NEW_LINE"); } public static void main ( String [ ] args ) { String s = " aeimqux " ; string_modify ( s . toCharArray ( ) ) ; } }