编程语言
首页 > 编程语言> > 1419. Minimum Number of Frogs Croaking (python)

1419. Minimum Number of Frogs Croaking (python)

作者:互联网

题目

在这里插入图片描述

解法:

这个题目有点意思的,比较巧妙。
我们需要找的是,这五个字母在某个时间出现的最大次数。限制条件是,每当遇到一个k的时候,放掉一只青蛙。同时需要检查给的字符串是不是无效,依照两个规则判断:

class Solution:
    def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
        # main idea: keep the appeared time of every char, we only need to find the maximum appeared time of one char in 'croak'. When 'k' encountered, meaning one croak finish, so we decrease the appeared time for all other chars by 1 (same as release one frog)
        # two situations for return -1: 1. if a char appeared, but the char supposed to appear before current does not exist, it's invalid 2. when finish, not all the char participated in forming a complete croak
        
        char2ind = {'c':1,'r':2,'o':3,'a':4,'k':5}
        # a list save the appeared times of every char
        char_appeared = [0]*6
        # make the first to be 1 for the situation when we encouter 'c'
        char_appeared[0] = 1
        
        min_frog = 0
        for c in croakOfFrogs:
            ind = char2ind[c]
            # if the previous one not exist, it's invalid
            if not char_appeared[ind-1]:
                return -1
            char_appeared[ind] += 1
            min_frog = max(min_frog,char_appeared[ind])
            
            # once 'k' appear, means we can free 1 frog
            if c == 'k':
                for i in range(1,6):
                    char_appeared[i] -= 1
        
        # if all the chars can not form several complete 'croak'
        for i in range(1,6):
            if char_appeared[i]:
                return -1
        
        return min_frog

标签:return,Frogs,Number,frog,char,python,ind,appeared,croak
来源: https://blog.csdn.net/qq_37821701/article/details/110227428