剑指 Offer 31. 栈的压入、弹出序列

107 阅读1分钟

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。

示例 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

提示:

0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。

java

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        if(pushed.length==0) return true;
        int first = popped[0];
        int index = getIndex(pushed,first);
        // 遍历poped数组
        for (int i = 1; i < popped.length; i++) {
            // 找到poped数组中出现的元素在pushed中出现的索引
            int indexIf = getIndex(pushed , popped[i]);
            // 判断找到的要出来的索引与前一个出来的元素的索引的大小关系
            // 如果要出来的在已出来的前前一个位置 返回false
            if(index-indexIf>1) return false;

            //否则的话删除pushed已出来的元素,将要出来的元素的索引赋给index 
            // 继续执行删除index的元素
            pushed = deleteIndex(pushed,index);
            index = getIndex(pushed , popped[i]);

            }
        return true;
        }
        
    // 获取元素的索引值
    int getIndex(int[] arr, int value) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return i;                  //字符串时,换为 equals
            }
        }
        return -1;//如果未找到返回-1
    }
    // 删除数组指定索引的元素
    int[] deleteIndex(int[] arr, int index){

        //定义存储删除元素后的arr的新数组newArr
        int[] newArr = new int[arr.length - 1];
        //定义新数组的索引newArr
        int j = 0;
        //for循环将未删除的元素按原保存顺序保存到新数组
        for (int i = 0; i < arr.length; i++) {
            //判断数组arr中需删除的索引index与循环到的i是否相同,不同时持续赋值j++,相同时则跳过继续比较
            if (index != i) {
                //index不等于i持续赋值
                newArr[j] = arr[i];
                //newArr[]向后移动一个元素
                j++;
            }
        }
        return newArr;
    }
}

解题思路:
依次遍历push数组,并存入栈中,当遇到栈顶元素和poped数组元素i位置相等时,循环出栈,如果栈最后是空返回true否则返回false

java

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        for(int num : pushed) {
            stack.push(num); // num 入栈
            while(!stack.isEmpty() && stack.peek() == popped[i]) { // 循环判断与出栈
                stack.pop();
                i++;
            }
        }
        return stack.isEmpty();
    }
}