劍指offer 31: 棧的壓入、彈出序列
阿新 • • 發佈:2020-07-17
package com.example.lettcode.offer; import java.util.Stack; /** * @Class ValidateStackSequences * @Description 劍指offer 31 棧的壓入、彈出序列 * 輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。 * 假設壓入棧的所有數字均不相等。例如,序列 {1,2,3,4,5} 是某棧 * 的壓棧序列,序列 {4,5,3,2,1} 是該壓棧序列對應的一個彈出序列, * 但 {4,3,5,1,2} 就不可能是該壓棧序列的彈出序列。 * <p> * 示例 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 * <p> * 示例 2: * 輸入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2] * 輸出:false * 解釋:1 不能在 2 之前彈出。 * <p> * 提示: * 0 <= pushed.length == popped.length <= 1000 * 0 <= pushed[i], popped[i] < 1000 * pushed 是 popped 的排列。 * @Author * @Date 2020/7/17 **/ public class ValidateStackSequences { // 使用輔助棧 public static boolean validateStackSequences(int[] pushed, int[] popped) { if (pushed.length != popped.length) return false; Stack<Integer> integerStack = new Stack<>(); int locationFirst = 0; int locationSecond = 0; while (locationFirst < pushed.length && locationSecond < popped.length) { // 棧為空或者棧頂元素與poped 當前元素不相同,則pushed元素入棧 while (integerStack.isEmpty() || (locationFirst < pushed.length && integerStack.peek() != popped[locationSecond])) { integerStack.push(pushed[locationFirst]); locationFirst++; } // 棧頂元素和poped當前元素相等則棧頂出棧 while (!integerStack.isEmpty() && locationSecond < popped.length && integerStack.peek() == popped[locationSecond]) { integerStack.pop(); locationSecond++; } } // 結束迴圈,判斷兩指標是否均指向最後一個元素的位置,即是否相等 return locationFirst == locationSecond; } public static void main(String[] args) { int[] pushed = new int[]{1, 2, 3, 4, 5}; int[] poped = new int[]{4, 5, 3, 2, 1}; boolean ans = validateStackSequences(pushed, poped); System.out.println("ValidateStackSequences demo01 result:" + ans); pushed = new int[]{1, 2, 3, 4, 5}; poped = new int[]{4, 3, 5, 1, 2}; ans = validateStackSequences(pushed, poped); System.out.println("ValidateStackSequences demo02 result:" + ans); } }