面试题31

https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/

这个题如果借栈来做的话,简直就是秒杀,但是我这里用了一个不借助栈的方法来实现。

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int slow = 0;
        int fast = 0;
        boolean[] visited = new boolean[pushed.length];
        for(;fast < pushed.length; fast++){
            int i = fast;
            while(i >= 0 && pushed[i] == popped[slow]){
                visited[i] = true;
                while( i >= 0 && visited[i]){
                    i--;
                }
                slow++;
            }
        }
        for(int i = 0; i < visited.length; i++){
            if(!visited[i]){
                return false;
            }
        }
        return true;
    }
}

使用visited数组表示原栈中的元素是否被匹配上。

中间的循环主要是用来寻找入栈和出栈的顺序是否匹配的。

原文地址:https://www.cnblogs.com/ZJPaang/p/12832052.html