|
| 1 | +## 1419. Minimum Number of Frogs Croaking |
| 2 | + |
| 3 | +``` |
| 4 | +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 croak in the given string. |
| 5 | +
|
| 6 | +A valid "croak" means a frog is printing 5 letters ‘c’, ’r’, ’o’, ’a’, ’k’ sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of valid "croak" return -1. |
| 7 | +
|
| 8 | + |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: croakOfFrogs = "croakcroak" |
| 13 | +Output: 1 |
| 14 | +Explanation: One frog yelling "croak" twice. |
| 15 | +Example 2: |
| 16 | +
|
| 17 | +Input: croakOfFrogs = "crcoakroak" |
| 18 | +Output: 2 |
| 19 | +Explanation: The minimum number of frogs is two. |
| 20 | +The first frog could yell "crcoakroak". |
| 21 | +The second frog could yell later "crcoakroak". |
| 22 | +Example 3: |
| 23 | +
|
| 24 | +Input: croakOfFrogs = "croakcrook" |
| 25 | +Output: -1 |
| 26 | +Explanation: The given string is an invalid combination of "croak" from different frogs. |
| 27 | +Example 4: |
| 28 | +
|
| 29 | +Input: croakOfFrogs = "croakcroa" |
| 30 | +Output: -1 |
| 31 | + |
| 32 | +
|
| 33 | +Constraints: |
| 34 | +
|
| 35 | +1 <= croakOfFrogs.length <= 10^5 |
| 36 | +All characters in the string are: 'c', 'r', 'o', 'a' or 'k'. |
| 37 | +``` |
| 38 | + |
| 39 | + |
| 40 | +```python |
| 41 | +class Solution: |
| 42 | + def minNumberOfFrogs(self, croakOfFrogs: str) -> int: |
| 43 | + |
| 44 | + if croakOfFrogs[0] != 'c' or croakOfFrogs[-1] != 'k': |
| 45 | + return -1 |
| 46 | + |
| 47 | + total_frogs = 0 |
| 48 | + no_of_frogs_croaking = 0 |
| 49 | + |
| 50 | + dic = {'c': 0, 'r':0, 'o':0, 'a': 0, 'k': 0} |
| 51 | + |
| 52 | + for c in croakOfFrogs: |
| 53 | + |
| 54 | + if c not in dic: |
| 55 | + return -1 |
| 56 | + |
| 57 | + if c == 'c': |
| 58 | + no_of_frogs_croaking +=1 |
| 59 | + dic[c] += 1 |
| 60 | + total_frogs = max(total_frogs, no_of_frogs_croaking) |
| 61 | + |
| 62 | + elif c == 'k': |
| 63 | + for char in 'croa': |
| 64 | + dic[char] -= 1 |
| 65 | + no_of_frogs_croaking -=1 |
| 66 | + else: |
| 67 | + dic[c] +=1 |
| 68 | + |
| 69 | + if no_of_frogs_croaking == 0 and list(dic.values()) == [0,0,0,0,0]: |
| 70 | + return total_frogs |
| 71 | + |
| 72 | + else: |
| 73 | + return -1 |
| 74 | +``` |
| 75 | + |
| 76 | + |
| 77 | +``` |
| 78 | +Runtime: 156 ms, faster than 87.04% of Python3 online submissions for Minimum Number of Frogs Croaking. |
| 79 | +Memory Usage: 15 MB, less than 39.20% of Python3 online submissions for Minimum Number of Frogs Croaking. |
| 80 | +``` |
0 commit comments