模块六:模拟——1419.数青蛙

文章目录

题目描述

题目链接:1419.数青蛙

算法原理

解法(模拟 + 分情况讨论)

模拟⻘蛙的叫声。

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

当遇到 'c' 这个字符的时候,我们去看看 'k' 这个字符有没有⻘蛙叫出来。如果有,就让这个⻘蛙继续去喊 'c' 这个字符;如果没有的话,就重新搞⼀个⻘蛙。

代码实现

cpp 复制代码
class Solution {
public:
    int minNumberOfFrogs(string croakOfFrogs) {
        const string croak = "croak";
        int n = croak.size();
        vector<int> hash(n);//用数组来模拟哈希表

        unordered_map<char,int> index;//[x,x所对应的下标]
        for(int i = 0;i < n;i++){
            index[croak[i]] = i;
        }

        for(auto ch : croakOfFrogs){
            if(ch == 'c'){
                if(hash[n - 1] != 0){
                    hash[n - 1]--;
                }
                hash[0]++;
            }
            else{
                int i = index[ch];
                if(hash[i - 1] == 0)return -1;
                hash[i - 1]--;
                hash[i]++;
            }
        }
        for(int i = 0;i < n - 1;i++){
            if(hash[i] != 0)return -1;
        }
        return hash[n - 1];
    }
};
相关推荐
ShineWinsu3 小时前
对于C++:IO流状态的详细解析
c++·面试·io·cin·io流状态·goodbit·failbit
数模竞赛Paid answer4 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆4 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
Lzg_na5 小时前
constexpr的优势
c++
想吃火锅10056 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
王维同学6 小时前
进程模块枚举、映像身份与线程启动地址关联
c++·windows·安全
hold?fish:palm6 小时前
24 回文链表
数据结构·c++·链表
举手6 小时前
Dispatcher模块剖析
linux·c++
Nil2086 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣7 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论