一刷剑指Offer_31:栈的压入和弹出序列

1、题目描述:
在这里插入图片描述
2、思路:

尝试按照 popped 中的顺序模拟一下出栈操作,如果符合则返回 true,否则返回 false。这里用到的贪心法则是如果栈顶元素等于 popped 序列中下一个要 pop 的值,则应立刻将该值 pop 出来。

使用一个栈来模拟该操作。将 pushed 数组中的每个数依次入栈,同时判断这个数是不是 popped 数组中下一个要 pop 的值,如果是就把它 pop 出来。最后检查栈是否为空。

在这里插入图片描述
3、实现方式1:

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
    
        Stack<Integer> stack = new Stack<Integer>();
        int j = 0;
        for(int i = 0;i <= pushed.length-1;i++){
            stack.push(pushed[i]);
            while(!stack.empty() && j <= popped.length-1 && stack.peek() == popped[j]){
                stack.pop();
                j++;
            }
        }
        return stack.empty();
    }
}

4、实现方式2:

class Solution2 {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int j = 0;

        /**
         * 1、如果栈中没有任何元素,len=0,调用peek()方法会抛出异常EmptyStackException
         * 2、当栈中还没有任何元素入栈时,判断stack.empty(),就不会判断后面的条件了
         * 3、当栈中有元素入栈后,判断stack.peek() != popped[poppedIndex]
         */
        for (int i = 0; i <= popped.length-1;i++) {
            while (j <= pushed.length-1 && (stack.empty() || stack.peek() != popped[i])){
                stack.push(pushed[j]);
                j++;
            }
            if(stack.peek()!=popped[i]){
                return false;
            }else{
                stack.pop();
            }
        }
        return true;
    }
}

5、测试类:

public class Main {
    public static void main(String[] args) {
        int[] pushed = {1,2,3,4,5};
//        int[] poped = {4,5,3,2,1};
        int[] poped = {4,3,5,1,2};

        Solution solution = new Solution();
        System.out.println(solution.validateStackSequences(pushed, poped));
    }
}
发布了716 篇原创文章 · 获赞 130 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_42764468/article/details/105324031