TypechoJoeTheme

Toasobi的博客

栈的压入,弹出顺序(中等)

本文最后更新于2023年03月16日,已超过553天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

这道题主要看你想没想到解题思路,想到了这道题就很简单

思路:将pushed按照顺序压入栈中,每压一次就要判读栈顶元素是否和poped数组首位相同,如果相同则弹栈,并且while继续比较后一位。最后如果栈为空,则表示该poped是pushed的弹出序列

代码如下(已加注释):

<div>class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        LinkedList<Integer> stack = new LinkedList<>();
        int index; //pushed下标位
        int index2 = 0; //poped下标位
        int point = 0; //栈中指针 为0则栈为空
        boolean flag = false; //代表传入的参数是否有进入下面的判断,没有进入说明pushed长度为0
        //按顺序压入
        for(index = 0;index < pushed.length; index++){
            flag = true;
            stack.push(pushed[index]);
            point ++;
            while(index2 < popped.length && point != 0 && stack.getFirst() == popped[index2]){
                stack.pop();
                point --;
                index2 ++;
            }
        }
        if(flag && point == 0){
            return true;
        } else if (!flag && popped.length == 0) {
            return true;
        }
        return false;
    }
}</div>
朗读
赞(0)
评论 (0)