题目描述:
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
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.
Note:
0 <= pushed.length == popped.length <= 10000 <= pushed[i], popped[i] < 1000pushedis a permutation ofpopped.pushedandpoppedhave distinct values.
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
int i = 0, j = 0;
stack<int> s;
while (i < pushed.size() && j < popped.size()) {
if (s.empty() || s.top() != popped[j]) {
s.push(pushed[i]);
i++;
}
else {
s.pop();
j++;
}
}
while (!s.empty() && s.top() == popped[j]) {
s.pop();
j++;
}
return i == pushed.size() && j == popped.size();
}
};

本文探讨了一种算法,用于判断给定的两个序列是否可以通过一系列的压栈(push)和弹栈(pop)操作从空栈得到。通过实例展示了如何进行有效的序列验证,并提供了详细的算法实现。
397

被折叠的 条评论
为什么被折叠?



