给定字符串str ,由三种不同类型的字符‘0’ 、 ‘1’和‘?’ 组成。 ,任务是通过替换“?”将给定的字符串转换为二进制字符串。与任一“0”或“1”的字符,使得0秒中的二进制字符串的计数和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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live