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.

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'.

My Solutions:

class Solution {

    // 每次看到一个c,代表一个新的蛙叫开始,青蛙数量++;每次看到一个k,青蛙数量--
    // 如果是别的字母,这个字母在croak之前的字母--;如果之前的字母已经是0了,说明有错,直接返回-1
    // 最后检查青蛙的数量是否等于0;如果是0,说明有的蛙叫没有达到k,返回-1
    public int minNumberOfFrogs(String str) {
        if (str.length() % 5 != 0) return -1;
        int frogs = 0, max = 0;
        int[] count = new int[5];
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int index = "croak".indexOf(c);
            if (index < 0) return -1;
            count[index]++;
            if (index == 0) { // 出现c
                frogs++; 
                max = Math.max(max, frogs);
            } else if (index == 4) {
                frogs--;
            }
            if (index > 0) {
                if (count[index - 1] == 0)  return -1;
                else count[index - 1]--;
            }
        }
        return frogs == 0 ? max : -1;

    }
}

Last updated