题解|好串

由于题目链接无法解析,我直接截图

此题要求我们判断字符串是否由 ab 插入操作得到的

根据要求,我们可以发现:一个符合条件的好串,其 a 的数量和 b 的数量绝对是一一对应的,且在一一对应的 ab 对里,a 在前,b 在后。

那么我们可以用一个栈,遍历字符串时,遇到 a 则入栈,遇到 b 则出栈。

如果出栈时,发现栈为空,那么

1. b的数量大于 a 的数量,不是好串

2. b 在前,a 在后,不是好串

如果遍历完成后,发现栈非空,那么

3. a 的数量大于 b 的数量,不是好串。

此外的,都是符合条件的好串。

整体代码如下:

#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<deque>
#include<cmath>
#include<string>
using namespace std;

int main(){
    string s;
    cin>>s;
    stack<char> a;
    
    for(char ch:s){
        if(ch=='a') a.push(ch);
        else{
            if(a.empty()){	//要出栈时,发现a为空,不是好串
                cout<<"Bad";
                return 0;
            }
            else a.pop();
        }
    }
    if(a.empty()) cout<<"Good";	//遍历后发现a不为空,不是好串
    else cout<<"Bad";
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务