Skip to content

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

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  bool winnerOfGame(string colors) {
    int countAAA = 0;
    int countBBB = 0;

    for (int i = 1; i + 1 < colors.length(); ++i)
      if (colors[i - 1] == colors[i] && colors[i] == colors[i + 1])
        if (colors[i] == 'A')
          ++countAAA;
        else
          ++countBBB;

    return countAAA > countBBB;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public boolean winnerOfGame(String colors) {
    int countAAA = 0;
    int countBBB = 0;

    for (int i = 1; i + 1 < colors.length(); ++i)
      if (colors.charAt(i - 1) == colors.charAt(i) && colors.charAt(i) == colors.charAt(i + 1))
        if (colors.charAt(i) == 'A')
          ++countAAA;
        else
          ++countBBB;

    return countAAA > countBBB;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def winnerOfGame(self, colors: str) -> bool:
    countAAA = 0
    countBBB = 0

    for a, b, c in zip(colors, colors[1:], colors[2:]):
      if 'A' == a == b == c:
        countAAA += 1
      elif 'B' == a == b == c:
        countBBB += 1

    return countAAA > countBBB