首页 > 其他分享 >LeetCode 1419. Minimum Number of Frogs Croaking

LeetCode 1419. Minimum Number of Frogs Croaking

时间:2022-10-06 11:34:08浏览次数:50  
标签:count frogs Frogs Number croakOfFrogs 1419 int frog croak

原题链接在这里:https://leetcode.com/problems/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.

Example 1:

Input: croakOfFrogs = "croakcroak"
Output: 1 
Explanation: One frog yelling "croak" twice.

Example 2:

Input: croakOfFrogs = "crcoakroak"
Output: 2 
Explanation: The minimum number of frogs is two. 
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".

Example 3:

Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.

Constraints:

  • 1 <= croakOfFrogs.length <= 105
  • croakOfFrogs is either 'c''r''o''a', or 'k'.

题解:

Whenever we see a 'c', frog count ++. When we see a 'k', frog count --.

When we see letters other than c, the previous letter letter of "croak" --. e.g. When we see a "o", the count of "r" --, count of "o" ++.

If previous letter count == 0 before --, then we could have a valid frog for that. Return -1.

Check if eventually count of frog is 0.

Time Complexity: O(n). n = croakOfFrogs.length().

Space: O(1).

AC Java:

 1 class Solution {
 2     public int minNumberOfFrogs(String croakOfFrogs) {
 3         int [] count = new int[5];
 4         int frogs = 0;
 5         int max = 0;
 6         for(int i = 0; i < croakOfFrogs.length(); i++){
 7             char c = croakOfFrogs.charAt(i);
 8             int ind = "croak".indexOf(c);
 9             count[ind]++;
10             if(ind == 0){
11                 frogs++;
12                 max = Math.max(max, frogs);
13             }else if(count[ind - 1]-- == 0){
14                 return -1;
15             }else if(ind == 4){
16                 frogs--;
17             }
18         }
19         
20         return frogs == 0 ? max : -1;
21     }
22 }

 

标签:count,frogs,Frogs,Number,croakOfFrogs,1419,int,frog,croak
From: https://www.cnblogs.com/Dylan-Java-NYC/p/16757269.html

相关文章