题解 | 验证栈序列

验证栈序列

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

#include <bits/stdc++.h>

using namespace std;

int main() {
    int q;
    cin>>q;
    while(q--)
    {
        int n;
        cin>>n;
        vector<int>a(n);
        vector<int>b(n);
        for(int i=0;i<n;i++)cin>>a[i];
        for(int i=0;i<n;i++)cin>>b[i];

        stack<int>s;
        bool is_ok=true;
        int j=0;
        int cnt=0;
        for(int i=0;i<n;i++)
        {
            s.push(a[i]);
            while(!s.empty()&&s.top()==b[j])
            {
                s.pop();
                j++;
                cnt++;//pop了几个数
            }
        }

        if(cnt<n)
        {
            for(;j<n;j++)
            {
                if(b[j]==s.top())
                {
                    cnt++;
                    s.pop();
                }
                else 
                {
                    is_ok=false;
                    break;
                }
            }   
        }

        if(is_ok&&cnt==n)
        cout<<"Yes"<<endl;
        else
        cout<<"No"<<endl;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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