Java实现——判断数组出栈顺序

来源:互联网 发布:键盘 编程 编辑:程序博客网 时间:2024/06/06 06:56

转自几个面试经典算法题Java解答(http://www.cnblogs.com/sunniest/p/4596182.html)题目八


两个整数数组,数组中没有重复元素。第一个数组按顺序入栈,判断第二个数组是否是该栈的弹出顺序。比如按照1、2、3、4、5入栈,出栈可以是2、1、5、4、3,但不会是4、5、2、1、3.

注意第9行intValue()方法的重要性,这与数组元素范围是否在-128~127之间有关。

import java.util.Stack;public class StackOrder {public boolean isPopByOrder(int[] num , Stack<Integer> s){Stack<Integer> in = new Stack<>();for(int i = 0 ; i < num.length ; i++){in.push(num[i]);while(!in.empty() && in.lastElement().intValue() == s.lastElement().intValue()){in.pop();s.pop();}}if(!in.empty()){return false;}return true;}public static void main(String[] args) {Stack<Integer> s = new Stack<>();int[] num = {201 , 202 , 203 , 204 , 205};int[] order = {202 , 201 , 205 , 204 , 203};for(int i = order.length - 1 ; i >= 0; i--){s.push(order[i]);}StackOrder so = new StackOrder();System.out.println(so.isPopByOrder(num, s));}}