【算法系列】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;
    }
};
相关推荐
uyeonashi34 分钟前
【Boost搜索引擎】构建Boost站内搜索引擎实践
开发语言·c++·搜索引擎
Smile丶凉轩4 小时前
Qt 界面优化(绘图)
开发语言·数据库·c++·qt
S01d13r5 小时前
LeetCode 解题思路 48(编辑距离、只出现一次的数字)
算法·leetcode·职场和发展
C_Liu_5 小时前
C语言:深入理解指针(5)
java·c语言·算法
small_wh1te_coder5 小时前
从经典力扣题发掘DFS与记忆化搜索的本质 -从矩阵最长递增路径入手 一步步探究dfs思维优化与编程深度思考
c语言·数据结构·c++·stm32·算法·leetcode·深度优先
枫景Maple5 小时前
LeetCode 45. 跳跃游戏 II(中等)
算法·leetcode
এ᭄画画的北北5 小时前
力扣-236.二叉树的最近公共祖先
算法·leetcode
z人间防沉迷k7 小时前
堆(Heap)
开发语言·数据结构·笔记·python·算法
不二狗7 小时前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
LabVIEW开发7 小时前
LabVIEW中样条插值实现及应用
算法·labview知识