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

📅  最后修改于: 2021-04-17 15:26:41             🧑  作者: Mango

给定一个字符串S由字符0,1,“?” ,任务是计算通过替换“?”形成的二进制字符串的所有可能组合用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.


输出:
2

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