栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

牛客网:AB2 栈的压入、弹出序列

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

牛客网:AB2 栈的压入、弹出序列

关于栈的练习。

方法一,使用一个模拟栈,模拟栈的栈入和栈出。

思路:

  1.  创建一个栈记录数据。
  2. 遍历出栈数组。
  3. 如果栈为空或者入栈顶的元素不等于出栈元素,直接入栈。
  4. 如果相等,出栈。
  5. 判断栈是否为空。 

代码如下

public boolean IsPopOrder(int [] pushA,int [] popA) {
        int len = pushA.length;
        // 辅助栈
        Stack stack = new Stack<>();
        // 双指针,记录下标, i 为出栈,j 为入栈
        int j = 0;

        for (int i = 0; i < len; i++){
            // z栈为空或者说栈顶的元素不等于出栈数,就入栈
            while (j < len && (stack.isEmpty() || popA[i] != stack.peek())){
                stack.push(pushA[j++]);
            }

            if (stack.peek() == popA[i]){
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }

方法二,数组优化。

public boolean IsPopOrder2(int [] pushA,int [] popA) {
        // 数组的大小
        int n = 0;
        int j = 0;

        for (int num : pushA){
            pushA[n] = num;

            while (n >= 0 && pushA[n] == popA[j]){
                j++;
                n--;
            }
            n++;
        }
        return n == 0;
    }

完整代码包括测试用例如下


import java.util.Stack;


public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
//        int[] pushA = {1,2,3,4,5}, popA = {4,5,3,2,1};
//        int[] pushA = {1,2,3,4,5}, popA = {4,3,5,1,2};
        int[] pushA = {2,1,0}, popA = {1,2,0};
        System.out.println(solution.IsPopOrder2(pushA, popA));
    }

    
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        int len = pushA.length;
        // 辅助栈
        Stack stack = new Stack<>();
        // 双指针,记录下标, i 为出栈,j 为入栈
        int j = 0;

        for (int i = 0; i < len; i++){
            // z栈为空或者说栈顶的元素不等于出栈数,就入栈
            while (j < len && (stack.isEmpty() || popA[i] != stack.peek())){
                stack.push(pushA[j++]);
            }

            if (stack.peek() == popA[i]){
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }

    
    public boolean IsPopOrder2(int [] pushA,int [] popA) {
        // 数组的大小
        int n = 0;
        int j = 0;

        for (int num : pushA){
            pushA[n] = num;

            while (n >= 0 && pushA[n] == popA[j]){
                j++;
                n--;
            }
            n++;
        }
        return n == 0;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930415.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号