题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
代码如下:
1 import java.util.Stack;
2
3 public class Solution {
4 public boolean IsPopOrder(
int [] pushA,
int [] popA) {
5 Stack<Integer> s =
new Stack<Integer>
() ;
6 int j = 0
; //边界条件判定
7 if(pushA.length!=popA.length||pushA.length ==0||popA.length==0
){
8 return false ;
9 } //如果两个序列的一个字符相同,则将该字符入栈再出栈,若不同,则将其入栈
10 for(
int i = 0 ;i < pushA.length ;i++
){
11 if(pushA[i] ==
popA[j]){
12 s.push(pushA[i]) ;
13 s.pop() ;
14 j++
;
15 }
16 else
17 s.push(pushA[i]) ;
18 }
19 if(s.empty()){
20 return true ;
21 }
22 while(!
s.empty()){
23 if(s.peek()!=
popA[j]){
24 return false ;
25 }
26 else
27 {
28 s.pop() ;
29 j++
;
30 }
31 }
32 return true ;
33 }
34 }
转载于:https://www.cnblogs.com/huntertoung/p/4779970.html