题目:
输入两个整数序列
第一个序列表示栈的压入顺序,第二个序列是弹出序列。
判断第二个序列是否是该栈的弹出序列。
假设所有的入栈的数字均不相等。
解答:
1 import java.util.*; 2 3 public class Solution { 4 5 public static void main(String[] args){ 6 Integer[] pushOrder = {1,2,3,4,5}; 7 Integer[] popOrder = {4,5,3,1,2}; 8 9 System.out.println(isRight(pushOrder, popOrder, 5)); 10 } 11 12 13 private static boolean isRight(Integer[] pushOrder, Integer[] popOrder, int n) { 14 Stack<Integer> stack = new Stack<Integer>(); 15 16 int count = 0; 17 for(int i = 0; i < popOrder.length; i++) { 18 if(!stack.isEmpty() && stack.peek() == popOrder[i]) { 19 stack.pop(); 20 } else { 21 22 if(count == pushOrder.length) { 23 return false; 24 } else { 25 26 do{ 27 stack.push(pushOrder[count++]); 28 }while(stack.peek() != popOrder[i] && count != pushOrder.length) 29 30 if(stack.peek() == popOrder[i]) { 31 stack.pop(); 32 } else { 33 return false; 34 } 35 } 36 } 37 } 38 39 return true; 40 } 41 }