简体   繁体   中英

Why is my function giving infinite output?

The question is to generate all binary strings from given pattern of 1, 0 and ?. The following code is what I have written and it is giving Infinite output. For example, If input is 1?1? , the output should be 1010, 1011 , 1110 , 1111

I am doing it in a iterative way using Queue.

static void fill(StringBuilder s)
{
    Queue<StringBuilder> q = new LinkedList<StringBuilder> () ;
    q.add(s);
    while(!q.isEmpty())
    {
        s = q.peek();
        int pos = s.indexOf("?");
        if(pos>=0)
        {
            StringBuilder s1 = new StringBuilder(s);
            s1.setCharAt(pos,'0');
            q.add(s1);
            StringBuilder s2 = new StringBuilder(s);            
            s1.setCharAt(pos,'1');
            q.add(s2);
        }
        else
            System.out.println(s);
        q.poll();    
    }
}

Note that you're modifying s1 in both cases:

if(pos>=0)
{
    StringBuilder s1 = new StringBuilder(s);
    s1.setCharAt(pos,'0');    // <-- Here s1 is fine
    q.add(s1);
    StringBuilder s2 = new StringBuilder(s);            
    s1.setCharAt(pos,'1');    // <-- You must use s2
    q.add(s2);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM