题目链接:栈的压入、弹出序列_牛客题霸_牛客网 (nowcoder.com)
题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
思路:可以先将数组转换为顺序表,这样可以不考虑下标的问题。
1.准备一个辅助栈,如果辅助栈为空或者栈顶不等于出栈数组当前元素,就持续将入栈数组加入栈中
2.栈顶等于出栈数组当前元素就出栈
3.当入栈数组访问完,出栈数组无法依次弹出,就是不匹配的,否则两个序列都访问完就是匹配的
代码如下:
import java.util.*;
public class Solution {
private List<Integer> intArrayToList(int[] array){
List<Integer> ans=new ArrayList<>();
for(int i:array){
//尾插
ans.add(i);
}
return ans;
}
public boolean IsPopOrder(int [] pushA, int [] popA) {
if(pushA.length!=popA.length){
return false;
}
List pushAList =intArrayToList(pushA);
List popAList=intArrayToList(popA);
//定义辅助栈
Deque<Integer> stack=new LinkedList<>();
//遍历出栈数组的每一个元素
while(!popAList.isEmpty()){
//头删,得到出栈元素
int r=(int)popAList.remove(0);
while(stack.isEmpty()||stack.peek()!=r){
//入栈数组为空,返回false
if(pushAList.isEmpty()){
return false;
}
//将入栈数组中的元素依次入栈
int e=(int)pushAList.remove(0);
stack.push(e);
}
//此时栈顶元素=出栈元素,出栈
stack.pop();
}
return true;
}
}
不转换为顺序表:
import java.util.*;
public class Solution {
public boolean IsPopOrder(int [] pushA, int [] popA) {
if(pushA.length!=popA.length){
return false;
}
int pushIndex=0; //初始化数组下标
int popIndex=0;
//定义辅助栈
Deque<Integer> stack=new LinkedList<>();
//遍历出栈数组的每一个元素
while(popIndex<popA.length){
//得到出栈元素
int r=popA[popIndex++];
while(stack.isEmpty()||stack.peek()!=r){
//入栈数组为空,返回false
if(pushIndex>=pushA.length){
return false;
}
//将入栈数组中的元素依次入栈
int e=pushA[pushIndex++];
stack.push(e);
}
//此时栈顶元素=出栈元素,出栈
stack.pop();
}
return true;
}
}