2038. Remove Colored Pieces if Both Neighbors are the Same Color

Difficulty:
Related Topics:
Similar Questions:

Problem

There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.

Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves** first**.

Assuming Alice and Bob play optimally, return true** if Alice wins, or return false if Bob wins**.

  Example 1:

Input: colors = "AAABABB"
Output: true
Explanation:
AAABABB -> AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.

Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.

Example 2:

Input: colors = "AA"
Output: false
Explanation:
Alice has her turn first.
There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.

Example 3:

Input: colors = "ABBBBBBBAAA"
Output: false
Explanation:
ABBBBBBBAAA -> ABBBBBBBAA
Alice moves first.
Her only option is to remove the second to last 'A' from the right.

ABBBBBBBAA -> ABBBBBBAA
Next is Bob's turn.
He has many options for which 'B' piece to remove. He can pick any.

On Alice's second turn, she has no more pieces that she can remove.
Thus, Bob wins, so return false.

  Constraints:

Solution

/**
 * @param {string} colors
 * @return {boolean}
 */
var winnerOfGame = function(colors) {
    var i = 0;
    var a = 0;
    var b = 0;
    while (i < colors.length) {
        var j = i;
        while (colors[j] === colors[i]) j++;
        if (j - i >= 3) {
            if (colors[i] === 'A') {
                a += j - i - 2;
            } else {
                b += j - i - 2;
            }
        }
        i = j;
    }
    return a > b;
};

Explain:

nope.

Complexity: