超精简完美算法:给定进栈顺序,判断一个序列是否为正确的出栈顺序
public class validateStackSequences {
public static boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<Integer>(); // 创建一个辅助栈
int i = 0;
for (int num : pushed) {
stack.push(num); // 将入栈数组中的数字一个个压入辅助栈中
while (!stack.isEmpty() && stack.peek() == popped[i]) {
// 如果辅助栈不为空,并且栈顶元素等于当前要弹出的数字,则将其弹出
stack.pop();
i++;
}
}
return i == popped.length; // 判断出栈数组是否完全被弹出栈
}
public static void main(String[] args) {
int[] pushed = {1, 2, 3, 4, 5};
int[] popped = {4, 5, 3, 2, 1};
System.out.println(validateStackSequences(pushed, popped)); // 输出 true
int[] pushed1 = {1, 2, 3, 4, 5};
int[] popped1 = {4, 3, 5, 1, 2};
System.out.println(validateStackSequences(pushed1, popped1)); // 输出 false
}
}