题解 | 验证栈序列

验证栈序列

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

#include <cstdio>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

bool isValidPopSequence(std::vector<int>& pushed, std::vector<int>& popped)
{
    std::stack<int> st;
    int i = 0;//指向popped当前位置

    for(int num : pushed)
    {
        st.push(num);
        while(!st.empty() && st.top() == popped[i])
        {
            st.pop();
            i++;
        }
    }
    return st.empty();
}

int main()
{
    int q = 0;
    int n = 0;
    int num = 0;
    cin >> q;
    getchar();
    vector<int> pushed;
    vector<int> popped;
    
    while(q--)
    {
        pushed.clear();
        popped.clear();
        cin >> n;
        getchar();

        for(int i = 0; i < n; i++)
        {
            cin >> num;
            pushed.push_back(num);
        }

        for(int i = 0; i < n; i++)
        {
            cin >> num;
            popped.push_back(num);
        }
        cout << (isValidPopSequence(pushed, popped) ? "Yes" : "No") << endl;
    }   
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

09-01 09:00
已编辑
四川旅游学院 运营
牛客55195891...:主要是专业不好,别的没毛病
牛客解忧铺
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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