📌  相关文章
📜  从给定模式生成所有二进制字符串

📅  最后修改于: 2022-05-13 01:57:08.260000             🧑  作者: Mango

从给定模式生成所有二进制字符串

给定一个包含 '0'、'1' 和 '?' 的字符串通配符,生成所有可以通过字符每个通配符替换为“0”或“1”来形成的二进制字符串。
例子 :

Input str = "1??0?101"
Output: 
        10000101
        10001101
        10100101
        10101101
        11000101
        11001101
        11100101
        11101101

方法 1(使用递归)
我们将下一个字符的索引传递给递归函数。如果当前字符是通配符 '?',我们将字符替换为 '0' 或 '1' 并递归剩余字符。如果我们到达它的结尾,我们会打印字符串。
下面是递归的实现。

C++
// Recursive C++ program to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
#include 
using namespace std;
 
// Recursive function to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
void print(string str, int index)
{
    if (index == str.size())
    {
        cout << str << endl;
        return;
    }
 
    if (str[index] == '?')
    {
        // replace '?' by '0' and recurse
        str[index] = '0';
        print(str, index + 1);
 
        // replace '?' by '1' and recurse
        str[index] = '1';
        print(str, index + 1);
 
        // No need to backtrack as string is passed
        // by value to the function
    }
    else
        print(str, index + 1);
}
 
// Driver code to test above function
int main()
{
    string str = "1??0?101";
 
    print(str, 0);
 
    return 0;
}


Java
// Recursive Java program to generate all
// binary strings formed by replacing
// each wildcard character by 0 or 1
import java.util.*;
import java.lang.*;
import java.io.*;
 
class binStr
{  
    // Recursive function to generate all binary
    // strings formed by replacing each wildcard
    // character by 0 or 1
    public static void print(char str[], int index)
    {
        if (index == str.length)
        {
            System.out.println(str);
            return;
        }
 
        if (str[index] == '?')
        {
            // replace '?' by '0' and recurse
            str[index] = '0';
            print(str, index + 1);
             
            // replace '?' by '1' and recurse
            str[index] = '1';
            print(str, index + 1);
             
            // NOTE: Need to backtrack as string
            // is passed by reference to the
            // function
            str[index] = '?';
        }
        else
            print(str, index + 1);
    }
 
    // driver code
    public static void main (String[] args)
    {
        String input = "1??0?101";
        char[] str = input.toCharArray();
        print(str, 0);
    }
}
 
// This code is contributed by Chhavi


Python3
# Recursive Python program to generate all
# binary strings formed by replacing
# each wildcard character by 0 or 1
 
# Recursive function to generate all binary
# strings formed by replacing each wildcard
# character by 0 or 1
def _print(string, index):
    if index == len(string):
        print(''.join(string))
        return
 
    if string[index] == "?":
 
        # replace '?' by '0' and recurse
        string[index] = '0'
        _print(string, index + 1)
 
        # replace '?' by '1' and recurse
        string[index] = '1'
        _print(string, index + 1)
 
        # NOTE: Need to backtrack as string
        # is passed by reference to the
        # function
        string[index] = '?'
    else:
        _print(string, index + 1)
 
# Driver code
if __name__ == "__main__":
 
    string = "1??0?101"
    string = list(string)
    _print(string, 0)
 
    # This code is contributed by
    # sanjeev2552
 
# Note: function name _print is used because
# print is already a predefined function in Python


C#
// Recursive C# program to generate all
// binary strings formed by replacing
// each wildcard character by 0 or 1
using System;
 
class GFG
{
    // Recursive function to generate
    // all binary strings formed by
    // replacing each wildcard character
    // by 0 or 1
    public static void print(char []str,
                             int index)
    {
        if (index == str.Length)
        {
            Console.WriteLine(str);
            return;
        }
 
        if (str[index] == '?')
        {
            // replace '?' by
            // '0' and recurse
            str[index] = '0';
            print(str, index + 1);
             
            // replace '?' by
            // '1' and recurse
            str[index] = '1';
            print(str, index + 1);
             
            // NOTE: Need to backtrack
            // as string is passed by
            // reference to the function
            str[index] = '?';
        }
        else
            print(str, index + 1);
    }
 
    // Driver Code
    public static void Main ()
    {
        string input = "1??0?101";
        char []str = input.ToCharArray();
        print(str, 0);
    }
}
 
// This code is contributed by nitin mittal.


PHP


Javascript


C++
// Iterative C++ program to generate all binary
// strings formed by replacing each wildcard
// character by 0 or 1
#include 
#include 
using namespace std;
 
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
void print(string str)
{
    queue q;
    q.push(str);
 
    while (!q.empty())
    {
        string str = q.front();
 
        // find position of first occurrence of wildcard
        size_t index = str.find('?');
 
        // If no matches were found,
        // find returns string::npos
        if(index != string::npos)
        {
            // replace '?' by '0' and push string into queue
            str[index] = '0';
            q.push(str);
 
            // replace '?' by '1' and push string into queue
            str[index] = '1';
            q.push(str);
        }
 
        else
            // If no wildcard characters are left,
            // print the string.
            cout << str << endl;
 
        q.pop();
    }
}
 
// Driver code to test above function
int main()
{
    string str = "1??0?101";
 
    print(str);
 
    return 0;
}


Python3
#we store processed strings in all (array)
#we see if string as "?", if so, replace it with 0 and 1
#and send it back to recursive func until base case is reached
#which is no wildcard left
 
res = []
def genBin(s):
    if '?' in s:
        s1 = s.replace('?','0',1) #only replace once
        s2 = s.replace('?','1',1) #only replace once
        genBin(s1)
        genBin(s2)
    else: res.append(s)
 
# Driver code
genBin("1??0?101")
print(res)
 
# This code is contributed by
# divay pandey


输出:
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

方法二(使用队列)
我们也可以通过使用迭代来实现这一点。这个想法是使用队列。我们在输入字符中找到第一次出现通配符的位置并将其替换为 '0' ,然后是 '1' 并将两个字符串字符串入队列。然后我们从队列中弹出下一个字符串,并重复该过程直到队列为空。如果没有字符串。
使用队列的迭代 C++ 实现。

C++

// Iterative C++ program to generate all binary
// strings formed by replacing each wildcard
// character by 0 or 1
#include 
#include 
using namespace std;
 
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
void print(string str)
{
    queue q;
    q.push(str);
 
    while (!q.empty())
    {
        string str = q.front();
 
        // find position of first occurrence of wildcard
        size_t index = str.find('?');
 
        // If no matches were found,
        // find returns string::npos
        if(index != string::npos)
        {
            // replace '?' by '0' and push string into queue
            str[index] = '0';
            q.push(str);
 
            // replace '?' by '1' and push string into queue
            str[index] = '1';
            q.push(str);
        }
 
        else
            // If no wildcard characters are left,
            // print the string.
            cout << str << endl;
 
        q.pop();
    }
}
 
// Driver code to test above function
int main()
{
    string str = "1??0?101";
 
    print(str);
 
    return 0;
}
输出:
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

方法 3(使用 str 和递归)

Python3

#we store processed strings in all (array)
#we see if string as "?", if so, replace it with 0 and 1
#and send it back to recursive func until base case is reached
#which is no wildcard left
 
res = []
def genBin(s):
    if '?' in s:
        s1 = s.replace('?','0',1) #only replace once
        s2 = s.replace('?','1',1) #only replace once
        genBin(s1)
        genBin(s2)
    else: res.append(s)
 
# Driver code
genBin("1??0?101")
print(res)
 
# This code is contributed by
# divay pandey
输出:
['10000101', '10001101', '10100101', '10101101', '11000101', '11001101', '11100101', '11101101']