本文共 787 字,大约阅读时间需要 2 分钟。
题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
代码实现:
import java.util.ArrayList;import java.util.Stack;public class Solution { //思路:用一个栈(s1)来模拟出栈的过程,这里用Stack来实现栈 //模拟过程:如果s1不为空,则看栈顶元素是否和出栈的第i个字符相等,如果相等 //就把栈顶元素出栈,比较新的栈顶元素和第i+1个元素;如果不等,那么按照入栈 //顺序将元素压栈,继续比较,如果元素已经全部压栈,但是s1中元素没有完成按顺 //序出栈,那么这个出栈顺序是不可能的 public boolean IsPopOrder(int [] pushA,int [] popA) { Stacks = new Stack<>(); for(int i = 0; i =pushA.length && popIndex>= popA.length){ return true; } else if(pushIndex>=pushA.length && !s.isEmpty() && (s.peek() != popA[popIndex])){ return false; } } }}
转载地址:http://osnqi.baihongyu.com/