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

📅  最后修改于: 2021-06-25 10:22:33             🧑  作者: Mango

给定字符串str ,它由三种不同类型的字符‘0’‘1’‘?’组成,任务是通过替换‘?’将给定的字符串转换为二进制字符串字符“ 0”“ 1” ,以使二进制字符串的0 s和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)