LC.P2103[环和杆]

方法一:位运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int countPoints(String rings) {
int n = rings.length();
int[] d = new int['Z'];
d['R'] = 1;
d['G'] = 2;
d['B'] = 4;
int[] mask = new int[10];
for (int i = 0; i < n; i += 2) {
char c = rings.charAt(i);
int j = rings.charAt(i + 1) - '0';
mask[j] |= d[c];
}
int ans = 0;
for (int x : mask) {
if (x == 7) ++ans;
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(m)$,$m$为杆的数量