验证栈序列
LeetCode传送门946. Validate Stack Sequences
题目
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
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:
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
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 of pushed.
思考线
解题思路
解答这道题的关键在于要记住这句话popped 是 pushed 的一个可能的出栈排列。
为啥这句话重要? 因为我们只需要按照这个可能出栈的模式进行模拟弹出即可。
- 现在我们用
stack来保存pushed中的数数据 - 每保存一个值就循环让 stack栈顶的元素和 poped的首个元素做比较,如果相同说明要弹出栈顶,而如果不相同说明此时不用弹出。
- 最后
pushed的值若为空,则stack的值也必然为空。若不为空则说明poped不是pushed的一种可能性,返回false. - 只要
pushed有值我们就一直重复执行1~3步。 - 若正常跳出第4步,我们只需要判断
stack是不是为空即可。
/**
* @param {number[]} pushed
* @param {number[]} popped
* @return {boolean}
*/
var validateStackSequences = function(pushed, popped) {
const stack = [];
while(pushed.length) {
if(pushed.length) {
stack.push(pushed.shift());
}
let pop = popped[0];
let last = stack[stack.length-1];
console.log(pop, last)
while(pop === last && typeof pop === "number") {
stack.pop()
popped.shift();
last = stack[stack.length -1];
pop = popped[0];
}
if(!pushed.length && stack.length) return false;
}
return stack.length === 0;
};Ï
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。