[LeetCode] Minimum Number of Frogs Croaking

1419. Minimum Number of Frogs Croaking

You are given the string croakOfFrogs, which represents a combination of the string “croak” from different frogs, that is, multiple frogs can croak at the same time, so multiple “croak” are mixed.

Return the minimum number of different frogs to finish all the croaks in the given string.

A valid “croak” means a frog is printing five letters ‘c’, ‘r’, ‘o’, ‘a’, and ‘k’ sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid “croak” return -1.

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
32
class Solution {
public:
int minNumberOfFrogs(string croakOfFrogs) {
int res = 0, now = 0;
unordered_map<char, int> freq;
for(auto& ch : croakOfFrogs) {
if(ch == 'c') {
now++;
freq[ch]++;
} else if(ch == 'r') {
if(freq['c'] == 0) return -1;
freq['c']--;
freq[ch]++;
} else if(ch == 'o') {
if(freq['r'] == 0) return -1;
freq['r']--;
freq[ch]++;
} else if(ch == 'a') {
if(freq['o'] == 0) return -1;
freq['o']--;
freq[ch]++;
} else if(ch == 'k') {
if(freq['a'] == 0) return -1;
freq['a']--;
now--;
} else return -1;
res = max(res, now);
}
if(now) return -1;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/22/PS/LeetCode/minimum-number-of-frogs-croaking/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.