给定一个字符串S由字符0,1,和“?” ,任务是计算通过替换“?”形成的二进制字符串的所有可能组合用0或1表示。
例子:
Input: S = “0100?110”
Output: 2
Explanation: Replacing each ‘?’s with ‘1’ and ‘0’, the count of such strings formed will be equal to “01001110” and “01000110”. Therefore, the total count of such strings formed is 2.
Input: S = “00?0?111”
Output: 4
方法:可以根据以下观察结果解决给定问题:
- 由于每个“?”可以用‘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)