31. 栈的压入、弹出序列
31. 栈的压入、弹出序列
思路:
时间复杂度:O(n)
核心代码:
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
if (pushed.empty() && pushed.empty()) return true;
if (pushed.size() != popped.size()) return false;
int i = 0;
stack<int> stk;
for (int x : pushed) {
stk.push(x);
while (stk.size() && stk.top() == popped[i]) {
i++;
stk.pop();
}
}
return stk.empty();
}
};
带main函数测试样例:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
if (pushed.empty() && pushed.empty()) return true;
if (pushed.size() != popped.size()) return false;
int i = 0;
stack<int> stk;
for (int x : pushed) {
stk.push(x);
while (stk.size() && stk.top() == popped[i]) {
i++;
stk.pop();
}
}
return stk.empty();
}
int main() {
vector<int> pushed = {1, 2, 3, 4, 5};
vector<int> popped = {4, 5, 3, 2, 1};
cout << validateStackSequences(pushed, popped) << endl;
return 0;
}