点击消除

点击消除

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;
}
算法竞赛之路 文章被收录于专栏

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

全部评论

相关推荐

zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

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