点击消除

点击消除

https://ac.nowcoder.com/acm/contest/5600/E

本题考察栈这一数据结构,可使用STL或直接用数组模拟。

直接用数组模拟码量更小。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 3e5 + 7;
const ll mod = 1e9 + 7;
char s[N];
char st[N];
int main(){
    cin>>s;
    int n=strlen(s),p=1;
    st[0]=s[0];
    for(int i=1;i<n;++i){
        if(s[i]==st[p-1])p--;
        else st[p++]=s[i];
    }if(p==0){cout<<'0'<<endl;return 0;}
    for(int i=0;i<p;++i)cout<<st[i];
    cout<<endl;
    return 0;
}

STL,比赛的时候因为忘记判断栈空情况,所以段错误了(然后就换了字符数组x

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 7;
const ll mod = 1e9 + 7;
int main(){
    string s;
    cin>>s;
    stack<char>st;
    int n=s.length();
    st.push(s[0]);
    for(int i=1;i<n;++i){
        if(st.empty())st.push(s[i]);//判断栈空
        else if(s[i]==st.top())st.pop();
        else st.push(s[i]);
    }if(st.empty()){cout<<'0'<<endl;return 0;}
    vector<char>ans;
    while(!st.empty()){
        ans.push_back(st.top());
        st.pop();
    }int len=ans.size();
    for(int i=len-1;i>=0;--i)cout<<ans[i];
    cout<<endl;
    return 0;
}
算法竞赛之路 文章被收录于专栏

整理、记录算法竞赛的好题

全部评论

相关推荐

Java大菜狗:纯纯招黑奴,一天还不到两百那么多要求,还不迟到早退,以为啥啊,给一点工资做一堆活,还以不拖欠员工工资为荣,这是什么值得骄傲的事情吗,纯纯***公司
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

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