给定字符串str ,它由三种不同类型的字符‘0’ , ‘1’和‘?’组成,任务是通过替换‘?’将给定的字符串转换为二进制字符串字符“ 0”或“ 1” ,以使二进制字符串的0 s和10的计数最大。
例子:
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
方法:想法是利用替换‘?’的事实以“0”字符字符总是最大化的0到10的计数。以下是观察结果:
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.
请按照以下步骤解决问题:
- 遍历字符串并检查当前字符是否为“?”或不。如果发现为真,则将当前字符替换为‘0’ 。
- 最后,打印字符串。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to maximize count of 0 and 10
// by replacing character '?' to '0' or '1'
void findMaxOccurence(string str, int N)
{
// Traverse the given string
for (int i = 0; i < N; i++) {
// If current character
// is '?'
if (str[i] == '?') {
// Replace str[i] to '0'
str[i] = '0';
}
}
cout << str <
Java
// Java program to implement
// the above approach
class GFG
{
// Function to maximize count of 0 and 10
// by replacing character '?' to '0' or '1'
static void findMaxOccurence(char[] str, int N)
{
// Traverse the given String
for (int i = 0; i < N; i++)
{
// If current character
// is '?'
if (str[i] == '?')
{
// Replace str[i] to '0'
str[i] = '0';
}
}
System.out.print(str);
}
// Driver Code
public static void main(String[] args)
{
// Given String
String str = "10?0?11";
int N = str.length();
findMaxOccurence(str.toCharArray(),N);
}
}
// This code is contributed by shikhasingrajput
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to maximize count of 0 and 10
// by replacing character '?' to '0' or '1'
static void findMaxOccurence(char[] str, int N)
{
// Traverse the given String
for (int i = 0; i < N; i++)
{
// If current character
// is '?'
if (str[i] == '?')
{
// Replace str[i] to '0'
str[i] = '0';
}
}
Console.Write(str);
}
// Driver Code
public static void Main(String[] args)
{
// Given String
String str = "10?0?11";
int N = str.Length;
findMaxOccurence(str.ToCharArray(),N);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to implement
# the above approach
# Function to maximize count of 0 and 10
# by replacing character '?' to '0' or '1'
def findMaxOccurence(str, N) :
# Traverse the given String
for i in range(N) :
# If current character
# is '?'
if (str[i] == '?') :
# Replace str[i] to '0'
str[i] = '0'
print("".join(str))
# Driver Code
# Given String
str = list("10?0?11")
N = len(str)
findMaxOccurence(str, N)
# This code is contributed by Dharanendra L V
Javascript
1000011
时间复杂度: O(N),其中N是字符串的长度
辅助空间: O(1)