GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

While loop is causing a infinite loop..

Hi, 

I am writing a program to remove consecutive duplicate characters in a String using below program:

static void main(String[] args){

String s = "abcdeedcbfgf";
removeDuplicate(s);

}

    static void removeDuplicate(String s) {
        String tmp = "";
        boolean isEligible = false;
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                tmp = s.substring(0, i) + s.substring((i + 2), s.length());
                System.out.println(tmp);
                s = tmp;
                isEligible = true;
                break;
            } 
        }

        System.out.println("s is:" + s);
        while ( isEligible)
            removeDuplicate(s);
    }

Once the string is reduced to afgf when there are no consecutive characters, it should stop as I am using flag in while. But the flag is getting true value.

I don't know how is it doing it?

Can somebody help me understand that?

The output should be: afgf

asked Jan 19, 2017 by Yogesh Malhotra
edited Jan 19, 2017 by Yogesh Malhotra

1 Answer

your boolean variable is local which is created each time when new function is called......when your recursion stopped and it backtrace previous isEligible is still true...

use global boolean variable

class Codechef
{
    static boolean isEligible;
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        String s = "abcdeedcbfgf";
        removeDuplicate(s);
    }
    static void removeDuplicate(String s) {
        String tmp = "";
         isEligible = false;
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                tmp = s.substring(0, i) + s.substring((i + 2), s.length());
                System.out.println(tmp);
                s = tmp;
                isEligible = true;
                break;
            } 
        }

        System.out.println("s is:" + s);
        while ( isEligible)
            removeDuplicate(s);
    }
}

answered Feb 1, 2017 by Jatin Kumar
...