【算法系列】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;
    }
};
相关推荐
科技苑6 小时前
C++ CAS与ABA问题详解,无锁编程的经典陷阱怎么解决?
c++·人工智能
GoAI7 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi7 小时前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M10 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen10 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
BaiPeter11 小时前
ZPL文件预览
开发语言·c++
心仪久了会沦陷12 小时前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
小此方12 小时前
[算法实战论:动态规划]背包问题概念,01不满背包问题,01满背包问题,背包问题的滚动数组空间优化
算法·动态规划
悠仁さん13 小时前
【C++】哈希表
c++·算法·散列表