📌  相关文章
📜  通过替换“?”来计算可能的排列在二进制字符串中的字符

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

给定一个由字符01‘?’组成的字符串S , 任务是计算通过替换‘?’形成的二进制字符串的所有可能组合。由01

例子:

方法:根据以下观察可以解决给定的问题:

  • 由于每个‘?’可以替换为‘0’‘1’ ,每个‘?’都有两种可能的选择字符。
  • 现在,任务减少到找到“?”的计数。 s,说计数
  • 因此,可以形成的不同字符串的总数为2 count

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

  • 计算“?”出现的次数,说
  • 打印2 count的值作为形成的字符串的结果组合。

下面是上述方法的实现:

C++14
#include 
 
using namespace std;
 
//Function to count all possible
//permutations of the string s
void countPermutations(string s){
 
    //Stores frequency of the
    //character '?'
    int count = 0;
 
    //Traverse the string
    for (char i:s){
        if (i == '?')
            count += 1;
      }
 
    //Print the answer
    cout<


Java
// Java program for the above approach
class GFG{
 
// Function to count all possible
// permutations of the string s
static void countPermutations(String s)
{
 
    // Stores frequency of the
    // character '?'
    int count = 0;
 
    // Traverse the string
    for (char i : s.toCharArray())
    {
        if (i == '?')
            count += 1;
      }
 
    // Print the answer
    System.out.print((int)Math.pow(2,count));
}
 
 
// Driver Code
public static void main(String[] args)
{
     
    // Given string S
  String s = "0100?110";
 
  // Function call to count
  // the number of permutations
  countPermutations(s);
}
}
 
// This code is contributed by code_hunt.


Python3
# Python3 program for the above approach
 
# Function to count all possible
# permutations of the string s
def countPermutations(s):
 
    # Stores frequency of the
    # character '?'
    count = 0
 
    # Traverse the string
    for i in s:
        if i == '?':
 
            # Increment count
            count += 1
 
    # Print the answer
    print(2**count)
 
# Driver Code
 
# Given string S
s = "0100?110"
 
# Function call to count
# the number of permutations
countPermutations(s)
 
# This code is contribute by mohit kumar 29.


C#
// C# program for above approach
using System;
 
public class GFG
{
   
// Function to count all possible
// permutations of the string s
static void countPermutations(string s)
{
 
    // Stores frequency of the
    // character '?'
    int count = 0;
 
    // Traverse the string
    foreach (char i in s)
    {
        if (i == '?')
            count += 1;
      }
 
    // Print the answer
    Console.WriteLine(Math.Pow(2,count));
}
 
// Driver code
public static void Main(String[] args)
{
   
    // Given string S
  string s = "0100?110";
 
  // Function call to count
  // the number of permutations
  countPermutations(s);
}
}
 
// This code is contributed by splevel62.


Javascript


输出:
2

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live