题解 | 验证栈序列
验证栈序列
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")
- 先将所有的pushed入栈,在入栈过程中,比较是否此时需要出栈:若pushed和此时进栈元素相同,则需要出栈,并且应该是一个while循环;此时辨别pushed的第i个元素后,则比较pushed的i+1个元素,故有j++
- 若j==n+1或者栈为空(表示所有的pushed元素都到popped中了),则表示是合法序列

查看17道真题和解析