Replace ' ? ' in a string such that no two adjacent characters are same | Java program for the above approach ; Function that replace all ' ? ' with lowercase alphabets such that each adjacent character is different ; Store the given String ; If the first character is ' ? ' ; Traverse the String [ 1 , N - 1 ] ; If the current character is ' ? ' ; Change the character ; Check equality with the previous character ; Check equality with the next character ; Check equality with the previous character ; If the last character is ' ? ' ; Change character ; Check with previous character ; Return the resultant String ; Driver Code ; Given String S ; Function Call
class GFG { static String changeString ( String S ) { char [ ] s = S . toCharArray ( ) ; int N = ( int ) S . length ( ) ; if ( s [ 0 ] == ' ? ' ) { s [ 0 ] = ' a ' ; if ( s [ 0 ] == s [ 1 ] ) { s [ 0 ] ++ ; } } for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( s [ i ] == ' ? ' ) { s [ i ] = ' a ' ; if ( s [ i ] == s [ i - 1 ] ) { s [ i ] ++ ; } if ( s [ i ] == s [ i + 1 ] ) { s [ i ] ++ ; } if ( s [ i ] == s [ i - 1 ] ) { s [ i ] ++ ; } } } if ( s [ N - 1 ] == ' ? ' ) { s [ N - 1 ] = ' a ' ; if ( s [ N - 1 ] == s [ N - 2 ] ) { s [ N - 1 ] ++ ; } } String ans = " " ; for ( int i = 0 ; i < s . length ; i ++ ) { ans += s [ i ] ; } return ans ; } public static void main ( String [ ] args ) { String S = " ? a ? a " ; System . out . print ( changeString ( S ) ) ; } }