package jianzhioffer;
import java.util.Scanner;
import java.util.Stack;
/** 根据入栈顺序,判断弹出序列是否会成为出栈顺序
* 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
* 假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,
* 但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
*
*/
public class Solution20 {
//依次判断入栈序列的每个元素,添加一个辅助栈,在每一个元素入栈之后,依次判断每个弹出序列的元素
public static boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length != popA.length ){
return false;
}
Stack<Integer> s = new Stack<Integer>();
int popAi = 0; //用来标识弹出序列的位置
for(int i = 0;i<pushA.length;i++){
s.push(pushA[i]);
while(!s.empty() && s.peek() == popA[popAi]){ 如果栈不为空,且栈顶元素等于弹出序列
s.pop();
popAi ++; //出栈,消除栈顶元素,弹出序列后移一位
}
}
return s.empty();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] pushA = new int[n];
for(int i = 0;i<n;i++){
pushA[i] = sc.nextInt();
}
int[] popA = new int[n];
for(int i = 0;i<n;i++){
popA[i] = sc.nextInt();
}
System.out.println(IsPopOrder(pushA,popA));
}
}
剑指offer题20
最新推荐文章于 2024-03-19 10:30:28 发布