image.png
纯模拟,定义total表示正在发出声音的青蛙,cnt[]将’croak’映射至0~4的下标作为字符计数器。遍历croakOfFrogs,遇到c时代表一只青蛙发出了叫声,total++,cnt[mapper]++。否则娃叫上一个字符是否已经在cnt中出现过,如不存在说明字符串不是一个合法串,返回答案-1;当遍历到的字符为k时,一只青蛙已经完成了一次蛙叫,total–;在遍历到c中对比到最大答案作为answer返回即可

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 int minNumberOfFrogs(String croakOfFrogs) {
Map<Character,Integer> map = new HashMap<>();
map.put('c',0);
map.put('r',1);
map.put('o',2);
map.put('a',3);
map.put('k',4);

int total = 0;
int answer = -1;
int[] cnt = new int[5];
for (int i = 0; i < croakOfFrogs.length(); i++) {
int mapper = map.get(croakOfFrogs.charAt(i));
if(mapper==0){
answer = Math.max(answer,++total);
cnt[mapper] ++;
}else {
if(cnt[mapper-1]==0) return -1;
cnt[mapper-1] --;
if(mapper==4){
total--;
}else{
cnt[mapper]++;
}
}
}
if(total>0) return -1;
return answer;
}
}

应该可以用贪心解决,等下午上课试试