946. 验证栈序列
946. Validate Stack Sequences
题目描述
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.
每日一算法2019/5/29Day 26LeetCode946. Validate Stack Sequences
Example 1:
Example 2:
Note:
Java 实现
import java.util.Stack;
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int n = pushed.length;
Stack<Integer> stack = new Stack<>();
for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) {
stack.push(pushed[pushIndex]);
while (popIndex < n && !stack.isEmpty() && stack.peek() == popped[popIndex]) {
stack.pop();
popIndex++;
}
}
return stack.isEmpty();
}
}
参考资料
LeetCode 946. 验证栈序列(Validate Stack Sequences) 26
原文:https://www.cnblogs.com/hglibin/p/10946672.html