置頂 0%

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

This question on LeetCode is a great practice for warm-ups. The approach I used was to count the consecutive occurrences of A and B excluding the ones at the beginning and end of the sequence. However, we can also use the Regular Expression to check who will win the game.

Quantity of Target

Question

Remove Colored Pieces if Both Neighbors are the Same Color

Solution

Regular Expression

For example, the String colors is AAAABBB and Alice got 2 moves and Bob only got 1 move.
We can use the replaceAll function to replace consecutive substrings longer than 2 characters with 2 character substrings and compare the length. If the length of replaceStrA(AABBB) is less than the length of replaceStrB(AAAABB), it means that Alice got more moves to do. Theresfore, we can return true if this case happened.

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean winnerOfGame(String colors) {
if(colors.length() <= 2) return false;

String replaceStrA = colors.replaceAll("A{3,}", "AA");
String replaceStrB = colors.replaceAll("B{3,}", "BB");

return replaceStrA.length() < replaceStrB.length();
}
}

Count number of possible moves

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean winnerOfGame(String colors) {
if(colors.length() <= 2) return false;

int countA = 0, countB = 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') countA++;
else countB++;
}
}

return countA > countB;
}
}

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public boolean winnerOfGame(String colors) {
if(colors.length() <= 2) return false;

int countA = 0, countB = 0;
int count = 0;
for(int i=1;i<colors.length();i++) {
if(colors.charAt(i-1) != colors.charAt(i)) {
if(colors.charAt(i-1) == 'A') {
countA += Math.max(0, (count - 1));
} else {
countB += Math.max(0, (count - 1));
}
count = 0;
} else {
count++;
}
}

// If there is a consecutive char at the end of the string like AAAABBBB
if(count != 0) {
if(colors.charAt(colors.length()-1) == 'A') {
countA += Math.max(0, (count - 1));
} else {
countB += Math.max(0, (count - 1));
}
}

return countA > countB;
}
}