LC.P1419[数青蛙]

方法一:计数+模拟

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
class Solution {
public int minNumberOfFrogs(String croakOfFrogs) {
int c = 0, r = 0, o = 0, a = 0, k = 0, ans = 0;
for (char x : croakOfFrogs.toCharArray()) {
if (x == 'c') {
if (k > 0) --k;
else ++ans;
++c;
} else if (x == 'r') {
--c;
++r;
} else if (x == 'o') {
--r;
++o;
} else if (x == 'a') {
--o;
++a;
} else {
--a;
++k;
}
if (c < 0 || r < 0 || o < 0 || a < 0) return -1;
}
if (c != 0 || r != 0 || o != 0 || a != 0) return -1;
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$