Make Palindrome binary string with exactly a 0 s and b 1 s by replacing wild card ? | C ++ program for the above approach ; Function to convert the given string to a palindrome with a 0 ' s ▁ and ▁ b ▁ 1' s ; Stores the size of the string ; Loop to iterate over the string ; If one of S [ i ] or S [ N - i - 1 ] is equal to ' ? ' , replace it with corresponding character ; Subtract the count of 0 from the required number of zeroes ; Subtract the count of 1 from required number of ones ; Traverse the string ; If both S [ i ] and S [ N - i - 1 ] are ' ? ' ; If a is greater than b ; Update S [ i ] and S [ N - i - 1 ] to '0' ; Update the value of a ; Update S [ i ] and S [ N - i - 1 ] to '1' ; Update the value of b ; Case with middle character ' ? ' in case of odd length string ; If a is greater than b ; Update middle character with '0' ; Update middle character by '1' ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string convertString ( string S , int a , int b ) { int N = S . size ( ) ; for ( int i = 0 ; i < N / 2 ; ++ i ) { if ( S [ i ] == ' ? ' && S [ N - i - 1 ] != ' ? ' ) { S [ i ] = S [ N - i - 1 ] ; } else if ( S [ i ] != ' ? ' && S [ N - i - 1 ] == ' ? ' ) { S [ N - i - 1 ] = S [ i ] ; } } a = a - count ( S . begin ( ) , S . end ( ) , '0' ) ; b = b - count ( S . begin ( ) , S . end ( ) , '1' ) ; for ( int i = 0 ; i < N / 2 ; ++ i ) { if ( S [ i ] == ' ? ' && S [ N - i - 1 ] == ' ? ' ) { if ( a > b ) { S [ i ] = S [ N - i - 1 ] = '0' ; a -= 2 ; } else { S [ i ] = S [ N - i - 1 ] = '1' ; b -= 2 ; } } } if ( S [ N / 2 ] == ' ? ' ) { if ( a > b ) { S [ N / 2 ] = '0' ; a -- ; } else { S [ N / 2 ] = '1' ; b -- ; } } if ( a == 0 && b == 0 ) { return S ; } else { return " - 1" ; } } int main ( ) { string S = "10 ? ? ? ? ?1" ; int a = 4 , b = 4 ; cout << convertString ( S , a , b ) ; return 0 ; }