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

关于栈的练习。

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

思路:

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

代码如下

public boolean IsPopOrder(int [] pushA,int [] popA) {
        int len = pushA.length;
        // 辅助栈
        Stack<Integer> 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;

/**
 * @author xnl
 * @Description:
 * @date: 2022/5/25   21:30
 */
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));
    }

    /**
     * 模拟栈:
     *      思路:用一个栈来记录入栈和出栈的数,有两个下标
     * @param pushA
     * @param popA
     * @return
     */
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        int len = pushA.length;
        // 辅助栈
        Stack<Integer> 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();
    }

    /**
     * 使用数组进行优化
     * @param pushA
     * @param popA
     * @return
     */
    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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值