Given string str, consisting of three different types of characters ‘0’, ‘1’ and ‘?’, the task is to convert the given string to a binary string by replacing the ‘?’ characters with either ‘0’ or ‘1’ such that the count of 0s and 10 in the binary string is maximum.
Examples:
Input: str = 10?0?11
Output: 1000011
Explanation:
Replacing str[2] = ‘0’ and str[4] = ‘0’ modifies string str = “1000011”.
The count of 0s in the string is 4 and the count of 10 in the string 1 which is the maximum possible count obtained from the given string.
Input: str = 1?1?
Output: 1010
Approach: The idea is to use the fact that replacing ‘?’ character with a ‘0’ character always maximizes the count of 0 and 10. Following are the observation:
If the character ‘?’ is followed by ‘0’ then replacing the character ‘?’ to ‘0’ increment the count of 0s.
If the character ‘1’ is followed by ‘?’ then replacing the character ‘?’ to ‘0’ increment the count of 0s and 10.
Follow the below steps to solve the problem:
- Traverse the string and check if the current character is ‘?’ or not. If found to be true, then replace the current character with ‘0’.
- Finally, print the string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMaxOccurence(string str, int N)
{
for ( int i = 0; i < N; i++) {
if (str[i] == '?' ) {
str[i] = '0' ;
}
}
cout << str <<endl;
}
int main()
{
string str = "10?0?11" ;
int N = str.length();
findMaxOccurence(str,N);
return 0;
}
|
Java
class GFG
{
static void findMaxOccurence( char [] str, int N)
{
for ( int i = 0 ; i < N; i++)
{
if (str[i] == '?' )
{
str[i] = '0' ;
}
}
System.out.print(str);
}
public static void main(String[] args)
{
String str = "10?0?11" ;
int N = str.length();
findMaxOccurence(str.toCharArray(),N);
}
}
|
C#
using System;
class GFG
{
static void findMaxOccurence( char [] str, int N)
{
for ( int i = 0; i < N; i++)
{
if (str[i] == '?' )
{
str[i] = '0' ;
}
}
Console.Write(str);
}
public static void Main(String[] args)
{
String str = "10?0?11" ;
int N = str.Length;
findMaxOccurence(str.ToCharArray(),N);
}
}
|
Python3
def findMaxOccurence( str , N) :
for i in range (N) :
if ( str [i] = = '?' ) :
str [i] = '0'
print ("".join( str ))
str = list ( "10?0?11" )
N = len ( str )
findMaxOccurence( str , N)
|
Javascript
<script>
function findMaxOccurence(str, N)
{
for ( var i = 0; i < N; i++) {
if (str[i] == '?' ) {
str[i] = '0' ;
}
}
document.write(str.join( '' ));
}
var str = "10?0?11" .split( '' );
var N = str.length;
findMaxOccurence(str,N);
</script>
|
Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(1)