题目描述
思路分析
模拟压栈出栈
代码展示
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> s1;
int cur = 0;
for (int i = 0; i < pushed.size(); i++) {
s1.push(pushed[i]);
while (cur < popped.size() && !s1.empty()) {
if (popped[cur] == s1.top()) {
s1.pop();
cur++;
}else {
break;
}
}
}
if (s1.empty()) {
return true;
}
return false;
}
};
结果分析
时间复杂度 O(N)
空间复杂度 O(N)