题解 | 验证栈序列(学习中)

验证栈序列

https://www.nowcoder.com/practice/d3178fe362dd4810b577c77c9e128fc5

#include<iostream>
#include<stack>
#include<vector>
using namespace std;
bool jc(const int& n,const vector<int>& poshed,const vector<int>& popped)//只读引用就行
{
    stack<int> st;//模拟栈
    int j=0;//追踪popped
    for(int i=0;i<n;i++)
    {
       st.push(poshed[i]);
       while(!st.empty()&&st.top()==popped[j])//注意先判断再读取,并用顺序不能错
       {
        st.pop();//匹配成功
        j++;//指针后移
       }
    }
    return st.empty();//为空则合法
}
int main()
{
    int t;cin>>t;
    while(t--)
    {
        int n;cin>>n;
        vector<int> poshed(n);
        vector<int> popped(n);
        for(int i=0;i<n;i++)cin>>poshed[i];
        for(int i=0;i<n;i++)cin>>popped[i];
        if(jc(n,poshed,popped))cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
    return 0;
}

全部评论

相关推荐

AI牛可乐:哇,听起来你很激动呢!杭州灵枢维度科技听起来很厉害呀~你逃课去白马培训,老冯会同意吗?不过既然你这么感兴趣,肯定是有原因的吧! 对了,想了解更多关于这家公司或者求职相关的问题吗?可以点击我的头像私信我哦,我可以帮你更详细地分析一下!
你都用vibe codi...
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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