LeetCode 5390. Counting frogs (brain hole question)

1. Title

Give you a string croakOfFrogs, which represents a combination of frog sounds (string "croak") from different frogs.
Since there can be multiple frogs croaking at the same time, multiple "croaks" are mixed in croakOfFrogs.
Please return the minimum number of different frogs required for all frogs in the simulated string .

Note: In order to sound the croak "croak", the frog must output the five letters 'c', 'r', 'o', 'a', 'k' in sequence.
If all five letters are not output, then it will not sound.

If the string croakOfFrogs is not a mixture of valid "croak" characters, please return -1.

示例 1:
输入:croakOfFrogs = "croakcroak"
输出:1 
解释:一只青蛙 “呱呱” 两次

示例 2:
输入:croakOfFrogs = "crcoakroak"
输出:2 
解释:最少需要两只青蛙,“呱呱” 声用黑体标注
第一只青蛙 "crcoakroak"
第二只青蛙 "crcoakroak"

示例 3:
输入:croakOfFrogs = "croakcrook"
输出:-1
解释:给出的字符串不是 "croak" 的有效组合。

示例 4:
输入:croakOfFrogs = "croakcroa"
输出:-1
 
提示:
1 <= croakOfFrogs.length <= 10^5
字符串中的字符只有 'c', 'r', 'o', 'a' 或者 'k'

Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/minimum-number-of-frogs-croaking
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

2. Problem solving

  • c, r, o, a, kThe number of characters at any time, not in this order
  • At the end the number must be equal
  • The maximum value of 5 characters at any time is the number of frogs needed
  • 5 characters full of a frog, then subtract it, you can reuse this frog later.
class Solution {
public:
    int minNumberOfFrogs(string croakOfFrogs) {
    	int i, frog=0, c, r, o, a, k;
    	c=r=o=a=k=i=0;
    	for(i = 0; i < croakOfFrogs.size(); ++i)
    	{
    		if(croakOfFrogs[i]=='c') c++;
    		else if(croakOfFrogs[i]=='r') r++;
    		else if(croakOfFrogs[i]=='o') o++;
    		else if(croakOfFrogs[i]=='a') a++;
    		else k++;
    		if(!(c>=r&&r>=o&&o>=a&&a>=k)) return -1;//次序不对
    		if(i == croakOfFrogs.size()-1 && !(a==r&&r==o&&o==a&&a==k))
    			return -1;//最后不相等
    		frog = max(frog,max(c,max(r,max(o,max(a,k)))));
    		if(c&&r&&o&&a&&k)//满了一只
    			c--,r--,o--,a--,k--;//减去它
    	}
    	return frog;
    }
};

Insert picture description here

Published 885 original articles · 2560 likes · 460,000+ views

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105618418