0
点赞
收藏
分享

微信扫一扫

牛客竞赛语法入门班栈、队列和STL习题C++版本参考代码及部分解析

肉肉七七 2022-02-04 阅读 35
c++

原题链接

E 好串

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
char a[60];
int main()
{
    stack<char> st;
    scanf("%s",a);
    int len = strlen(a);
    for (int i = 0;i < len;i++)
    {
        if (a[i] == 'a') st.push(a[i]);
        else if (a[i] == 'b' && st.empty()) st.push(a[i]);
        else if (a[i] == 'b' && st.top() == 'a') st.pop();
    }
    if (!st.empty()) cout << "Bad" << endl;
    else cout << "Good" << endl;
    return 0;
}

H 吐泡泡

#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stack>
using namespace std;
char c[110];
int main()
{
    stack<char> st;
    while (~scanf("%s",c))//数据有多组
    {
        int len = strlen(c);
        for (int i = 0;i < len;i++)
        {
            if (st.empty()) st.push(c[i]);//若栈空,则直接入栈
            else if (!st.empty())//若栈不空,分类讨论
            {
                if (st.top() == 'O' && c[i] == 'O') st.pop();//两个大O则出栈
                else if (st.top() == 'O' && c[i] == 'o') st.push(c[i]);//一大O一小o则入栈
                else if (st.top() == 'o' && c[i] == 'O') st.push(c[i]);//一小o一大O则入栈
                else if (st.top() == 'o' && c[i] == 'o')//两个o变O
                {
                    st.pop();
                    if (!st.empty() && st.top() == 'O') st.pop();//弹出小o之后栈顶是大O
                    else st.push('O');
                }
            }
        }
        string s = "";//空串
        while (!st.empty())
        {
            s += st.top();
            st.pop();
        }
        reverse(s.begin(),s.end());//从栈底输出栈中元素
        cout << s << endl;//切记换行
    }
    return 0;
}
举报

相关推荐

0 条评论