思路就是:将数组A[i]依次压入栈,若栈顶元素和b[j]相等,将栈顶元素出栈
j++,这里用一个while循环判断,若不相等,则继续入栈,直到A为空,判断
栈是否为空。
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA==null&&popA!=null)
return false;
Stack<Integer> stack=new Stack<>();
int i=0,j=0;
for(;i<pushA.length;i++){
stack.push(pushA[i]);
while(!stack.isEmpty()&&stack.peek()==popA[j]){
//这里一定要判断栈里还有没有元素,有的话才能调用peek()
stack.pop();
j++;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int[] A=new int[n],B=new int[n];
for(int i=0;i<n;i++){
A[i]=scan.nextInt();
}
for (int i = 0; i <n ; i++) {
B[i]=scan.nextInt();
}
boolean result=new Solution().IsPopOrder(A,B);
System.out.println(result);
}
}
剑指offer 栈的压入和弹出序列
最新推荐文章于 2023-02-20 09:12:06 发布