1. 题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
2. 解题思路
(1)从题目可以知道这是一个栈知识,所以一开始我们可以声明一个容器(栈),具体做法就是第一次遍历第一个数组,同时对比它们是否相同,最后再遍历一次比较它们是否相同即可。
(2)大概思路是一样的,不过这个代码看起来好点。
3. 代码实现
(1)
import java.util.*;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack<>();
int count = 0;
for (int i = 0; i < pushA.length; i++){
if(pushA[i] == popA[count])
{
count++;
}else {
stack.push(pushA[i]);
}
}
for (int j = count; j < popA.length; j++){
if (stack.pop() != popA[j])
return false;
}
return true;
}
}
(2)
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack<>();
if(pushA.length != popA.length)
return false;
int j =0;
for(int i =0 ; i < pushA.length ; i++){
if(popA[j] == pushA[i]){
j++;
}else{
stack.push(pushA[i]);
}
}
while(j != popA.length)
{
if(stack.pop() != popA[j])
return false;
j++;
}
return true;
}
}