946. Validate Stack Sequences
946. Validate Stack Sequences
题目: https://leetcode.com/problems/validate-stack-sequences/
难度: Medium
题意:
- 两个数组
- 问入栈顺序为pushed数组,是否可能出栈顺序为popped数组
思路:
- 模拟即可。我们把新建一个栈,按照pushed数组的顺序一个一个丢进去,并且,检查popped数组前面的数组,如果可以弹出就弹出。到最后判断栈是否为空即可
解法:
class Solution {
public:
int stack[1010];
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
int n = 0, j = 0;
for (int i = 0;i < pushed.size();i++) {
stack[n++] = pushed[i];
while (n > 0 && stack[n - 1] == popped[j]) {
n--;
j++;
}
}
if (n == 0) {
return true;
} else {
return false;
}
}
};