题目:
Given two integer arrays pushed
and popped
each with distinct values, return true
if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false
otherwise.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] Output: false Explanation: 1 cannot be popped before 2.
Constraints:
1 <= pushed.length <= 1000
0 <= pushed[i] <= 1000
- All the elements of
pushed
are unique. popped.length == pushed.length
popped
is a permutation ofpushed
.
思路:
模拟题,直接用一个栈来模拟即可。按顺序往栈内加入pushed里的元素,每一次加入后check栈是否为空和栈顶元素是不是当前popped的元素,如果是的话可以删除,即模拟出栈。正确的出栈顺序下应该正好遍历了一次popped,否则就是错误的。以例子2来看,栈内为[1,2,3,4]时,出栈,4被消掉,此时cur为1,即指向3;之后加入5,栈内为[1,2,3,5],同时cur指向的是3,不会被删除,循环结束,cur并没有遍历完整个popped,因此返回false。
代码:
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
int cur = 0;
stack<int> st;
for (auto i : pushed) {
st.push(i);
while (st.size() && st.top() == popped[cur]) {
st.pop();
cur++;
}
}
return cur == popped.size();
}
};