题解 | 点击消除

点击消除

https://www.nowcoder.com/practice/8d3643ec29654cf8908b5cf3a0479fd5

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 300000 + 10;
// 用数组模拟栈,存储字符
char st[MAXN];
// 栈顶指针,初始可看作栈为空
int top;

int main()
{
    string s;
    cin >> s;
    // 遍历输入的字符串
    for(int i = 0; i < s.size(); i++)
    {
        // 若栈不为空,且栈顶字符和当前字符相同
        if(top && st[top] == s[i])
        {
            // 弹出栈顶字符
            top--;
        }
        else
        {
            // 否则将当前字符压入栈
            st[++top] = s[i];
        }
    }
    // 若栈不为空
    if(top)
    {
        // 输出栈中剩余的字符
        for(int i = 1; i <= top; i++)
        {
            cout << st[i];
        }
        cout << endl;
    }
    else
    {
        // 若栈为空,输出 0
        cout << 0 << endl;
    }
    return 0;
}

全部评论

相关推荐

牛客10001:问就是六个月,全国可飞,给钱就干
点赞 评论 收藏
分享
抱抱碍事梨a:三点建议,第一点是建议再做一个项目,把自我介绍部分顶了,第二点是中南大学加黑加粗,第三点是建议加v详细交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务