Finding 3 consecutive duplicate char characters in an array?

Tags: ,



I am having some problems trying to replace 3 consecutive duplicate char characters in an array. I want to find those 3 values and replaces them with x’s. So far this is what I have:

public static char[] replaceSets(char [] input) {
    for (int i = 0; i < input.length; i++) {
        for(int j = i+1; j < input.length; j++)
            for(int k = j+1; k < input.length; k++) {
                if ((input[i] == input[j]) && (input[j] == input[k])) {
                    input[i] = 'x';
                    input[j] = 'x';
                    input[k] = 'x';
                }
            }
    }
    return input;
}

However, if I have:

char[] input = {'r','y','y','r','r','g','b','y','y','y','r','g'};

It prints out:

xxxxxgbxyyrg

But, it should be:

ryyrrgbxxxrg

Answer

You do not need 3 loops to do this. You can take the following approach:

public static char[] replaceSets(char[] input) {
    if (input.length < 3) {
        return input;
    }

    for (int i = 0; i < input.length - 3; ++i) {
        if (input[i] == input[i + 1] && input[i + 1] == input[i + 2]) {
            input[i] = 'x';
            input[i + 1] = 'x';
            input[i + 2] = 'x';
            i += 2;
        }
    }

    return input;
}

The function loops over the character array and tries to compare if characters at i, i + 1, i + 2 positions are same. If so simply replace them with 'x'.



Source: stackoverflow