How to generate all possible binary strings by replacing ? from a given pattern in Java

1 Answer

0 votes
import java.util.LinkedList; 
import java.util.Queue; 

public class MyClass {
    private static void generate_all_possible_binary_strings(String str) {
    	Queue<String> q = new LinkedList<>();
        q.add(str);
     
        while (!q.isEmpty()) {
            String temp = q.remove();

            int index = temp.indexOf('?');
            if (index != -1) {
                temp = temp.substring(0,index) + '0' + temp.substring(index+1);
                q.add(temp);
     
                temp = temp.substring(0,index) + '1' + temp.substring(index+1);
                q.add(temp);
            }
     
            else {
                System.out.println(temp);
            }
     
        }
    }
    public static void main(String args[]) {
        String str = "1?0?1";

	    generate_all_possible_binary_strings(str);
    }
}





/*
run:

10001
10011
11001
11011

*/


 



answered Aug 24, 2023 by avibootz
edited Aug 24, 2023 by avibootz
...