Remove Colored Pieces if Both Neighbors are the Same Color

medium math string greedy game theory

Problem

Alice and Bob alternate turns. Alice can remove an 'A' whose both neighbors are 'A'; Bob does the same with 'B'. Alice moves first; the loser is the first one unable to move. Return true if Alice wins.

Inputcolors = "AAABABB"
Outputtrue
Alice has 1 AAA center, Bob has 0 BBB centers — Alice wins.

def winner_of_game(colors):
    a = b = 0
    for i in range(1, len(colors) - 1):
        if colors[i - 1] == colors[i] == colors[i + 1]:
            if colors[i] == 'A':
                a += 1
            else:
                b += 1
    return a > b
function winnerOfGame(colors) {
  let a = 0, b = 0;
  for (let i = 1; i < colors.length - 1; i++) {
    if (colors[i - 1] === colors[i] && colors[i] === colors[i + 1]) {
      if (colors[i] === 'A') a++;
      else b++;
    }
  }
  return a > b;
}
class Solution {
    public boolean winnerOfGame(String colors) {
        int a = 0, b = 0;
        for (int i = 1; i < colors.length() - 1; i++) {
            if (colors.charAt(i - 1) == colors.charAt(i) && colors.charAt(i) == colors.charAt(i + 1)) {
                if (colors.charAt(i) == 'A') a++;
                else b++;
            }
        }
        return a > b;
    }
}
bool winnerOfGame(string colors) {
    int a = 0, b = 0;
    for (int i = 1; i + 1 < (int)colors.size(); i++) {
        if (colors[i-1] == colors[i] && colors[i] == colors[i+1]) {
            if (colors[i] == 'A') a++;
            else b++;
        }
    }
    return a > b;
}
Time: O(n) Space: O(1)