【算法系列】leetcode1419 数青蛙 --模拟

一、题目

二、思路

模拟⻘蛙的叫声。

当遇到 'r' 'o' 'a' 'k' 这四个字符的时候,我们要去看看每⼀个字符对应的前驱字符,有没有⻘蛙叫出来。如果有⻘蛙叫出来,那就让这个⻘蛙接下来喊出来这个字符;如果没有则为异常字符串,直接返回 -1

当遇到'c'这个字符的时候,我们去看看'k'这个字符有没有⻘蛙叫出来。如果有,就让

这个⻘蛙继续去喊'c'这个字符;如果没有的话,就⻘蛙数加1。

三、代码

我的版本

cpp 复制代码
#include <unordered_map>
class Solution {
public:
    int minNumberOfFrogs(string croakOfFrogs) {
    string str="croak";
    unordered_map<char,int> index;
    int len=str.size();
    vector<int> cnt(5,0);
    for(int i=0;i<len;++i)
    index[str[i]]=i;
    for(auto e:croakOfFrogs)
    {   
        if(e=='c')
        {
            if(cnt[len-1]!=0) cnt[len-1]--;  
                cnt[0]++;
        }
        else
        {
            if(cnt[index[e]-1]==0)return -1;
            cnt[index[e]-1]--;
            cnt[index[e]]++;
        }
    }
    for(int i=0;i<len-1;++i)
    {
        if(cnt[i]!=0)return -1;
    }
    return cnt[len-1];
    }
};

deepseek深度学习版本:

cpp 复制代码
#include <unordered_map>
class Solution {
public:
    int minNumberOfFrogs(string croakOfFrogs) {
    // 定义字符到阶段的映射
    unordered_map<char, int> charToIdx = {{'c', 0}, {'r', 1}, {'o', 2}, {'a', 3}, {'k', 4}};
    vector<int> counts(5, 0); // 分别代表c, r, o, a, k阶段的青蛙数目
    int maxFrogs = 0;

    for (char ch : croakOfFrogs) {
        // 检查字符是否有效
        if (charToIdx.find(ch) == charToIdx.end()) {
            return -1;
        }
        int idx = charToIdx[ch];

        if (idx == 0) {
            // 处理字符c,优先复用k阶段的青蛙
            if (counts[4] > 0) {
                counts[4]--;
                counts[0]++;
            } else {
                counts[0]++;
            }
        } else {
            // 处理其他字符,需要前一个阶段有青蛙
            int prev = idx - 1;
            if (counts[prev] == 0) {
                return -1;
            }
            counts[prev]--;
            counts[idx]++;
        }
        // 计算当前活跃的青蛙数目
        int currentSum = counts[0] + counts[1] + counts[2] + counts[3] + counts[4];
        maxFrogs = max(maxFrogs, currentSum);
    }

    // 检查所有非k阶段的数目是否为0
    for (int i = 0; i < 4; i++) {
        if (counts[i] != 0) {
            return -1;
        }
    }

    return maxFrogs;
    }
};
相关推荐
王老师青少年编程8 分钟前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程9 分钟前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒11 分钟前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣11 分钟前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮29 分钟前
Opus 4.7 来了,我并不建议你升级
算法
leaves falling44 分钟前
C++模板进阶
开发语言·c++
无敌昊哥战神1 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__1 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode
再卷也是菜1 小时前
算法提高篇(1)线段树(上)
数据结构·算法
py有趣1 小时前
力扣热门100题之单词拆分
算法·leetcode