【算法系列】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;
    }
};
相关推荐
千里码aicood3 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
码匠许师傅3 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
做cv的小昊3 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له4 小时前
World-In-World: World Models in a Closed-Loop World
算法
无名猿4 小时前
new/delete 与 malloc/free:为什么绝对不能混用
c++·内存管理·现代c++·踩坑记录
2601_962218615 小时前
C++中decltype关键字的实现
开发语言·c++
Discipline10296 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
繁华的地方不一定留下你的脚印6 小时前
C++ std::variant 与 std::visit:安全保存多种类型,写清每个处理分支
开发语言·c++
XuCoder6 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法