文章目录
题目链接:
题目描述:

解法
直接用栈来验证栈序列。
C++ 算法代码:
cpp
class Solution
{
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped)
{
// 验证栈序列算法
// 基本思路:模拟栈的操作,看是否能够按照给定的顺序实现出栈
stack<int> st; // 用栈来模拟入栈和出栈操作
int i = 0; // 当前处理的popped数组的索引
int n = popped.size(); // popped数组的长度
// 遍历pushed数组中的每个元素
for(auto x : pushed)
{
st.push(x); // 将当前元素入栈
// 尝试执行出栈操作:只要栈顶元素等于当前需要出栈的元素,就执行出栈
while(st.size() && st.top() == popped[i])
{
st.pop(); // 弹出栈顶元素
i++; // 移动到popped数组的下一个元素
}
}
// 如果所有元素都能正确出栈,则i应该等于n
return i == n;
}
};