📌  相关文章
📜  代替 '?'将给定的字符串转换为最大计数为“0”和“10”的二进制字符串

📅  最后修改于: 2021-09-07 03:29:06             🧑  作者: Mango

给定字符串str ,由三种不同类型的字符‘0’‘1’‘?’ 组成。 ,任务是通过替换“?”将给定的字符串转换为二进制字符串与任一“0”“1”的字符,使得0秒中的二进制字符串的计数和10是最大的。

例子:

方法:这个想法是使用替换‘?’的事实“0”字符字符总是最大化的010的计数。以下是观察:

请按照以下步骤解决问题:

  • 遍历字符串并检查当前字符是否为‘?’或不。如果发现为真,则将当前字符替换为‘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