题解 | 验证栈序列

验证栈序列

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

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

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

        stack<int> stk;
        int j = 0;
        for(int i = 0; i < n; i++){
            stk.push(pushed[i]);
            while(!stk.empty() && stk.top() == popped[j]){
                stk.pop();
                j++;
            }
        }
        if(stk.empty()) cout << "Yes";
        else cout << "No";
        cout << endl;
    }
}
// 64 位输出请用 printf("%lld")
  1. 先将所有的pushed入栈,在入栈过程中,比较是否此时需要出栈:若pushed和此时进栈元素相同,则需要出栈,并且应该是一个while循环;此时辨别pushed的第i个元素后,则比较pushed的i+1个元素,故有j++
  2. 若j==n+1或者栈为空(表示所有的pushed元素都到popped中了),则表示是合法序列
全部评论

相关推荐

04-17 23:48
西北大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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