题解 | 好串

好串

https://www.nowcoder.com/practice/9b072237ebdd4dd99562f01cbf594fac

这道题其实就是括号题的变种,用的还是栈的逻辑

#include  <bits/stdc++.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
    stack<char> st;
    string s;

    cin>>s;
     
    for(int i=0;i<s.size();i++){
        // 开始遍历
        // 若遍历到a,则进栈
        if(s[i]=='a'){
            st.push(s[i]);
        }else{
            // 遍历到b,先判断栈是否为空,为空则bad,若栈顶元素为a则让a出栈与b匹配
            if(st.empty()){
                cout<<"Bad";
                return 0;
            }else {
                if(st.top()!='a')   
                    {cout<<"Bad"; 
                    return 0;}
                else st.pop();
            }
        }
    }
    // 遍历完最后,栈内元素必为空
    if(st.empty()){
        cout<<"Good";
    }else {
        cout<<"Bad";
    }

     return 0;
}
 

全部评论

相关推荐

牛客51274894...:照片认真的吗,找个专门拍证件照的几十块钱整端正点吧,要不就别加照片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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