目录
一,题目描述
英文描述
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.
中文描述
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
示例与说明
示例 1:
示例 2:
![]()
提示:
![]()
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-stack-sequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二,解题思路
用两个指针i、j分别指向pushed、popped。
以i指针为基准遍历pushed序列。每次循环先将pushed[i]压入堆栈,然后根据栈顶和popped序列中的值是否相等来判断是否弹栈以及j指针递增。
三,AC代码
Java
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> record = new Stack<>();
for (int i = 0, j = 0; i < pushed.length; i++) {
record.push(pushed[i]);
while (!record.isEmpty() && record.peek() == popped[j]) {
record.pop();
j++;
}
}
return record.isEmpty();
}
}
四,解题过程
第一博
一发入魂~