剑指offer题20
来源:互联网 发布:手机数据恢复原理 编辑:程序博客网 时间:2024/06/05 20:16
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));}}
阅读全文
0 0
- 剑指offer题20
- 【剑指offer】11-20题
- 【剑指offer】题20:顺时针打印矩阵
- 剑指offer-20
- 【16-20】剑指offer
- 剑指Offer-20
- 剑指offer第一题
- 剑指offer-题
- 剑指offer第一题
- 剑指Offer第一题
- 剑指offer(题三)
- 剑指offer第二题
- 剑指offer第三题
- 剑指offer第四题
- 剑指offer第五题
- 剑指offer题一
- 剑指offer题二
- 剑指offer题七
- Linux GDB程序调试工具使用简介
- tensorflow object_dection API错误处理
- 大,小端问题
- Qt: 数据转换
- 确实是闲的 整理一下java知识
- 剑指offer题20
- 【Spring】Spring Framework Reference Documentation中文版30
- 关键字优化好不好的8个必须指标
- Linux GDB程序调试工具使用简介
- springboot-整合mybatis
- UVa12563--Jin Ge Jin Qu hao DP(01背包)
- Android JNI获取上下文Context
- apach kafka议定书指南
- 欢迎使用CSDN-markdown编辑器