Stack push, pop sequence (to prove safety offer_31)

Title Description


Two input sequence of integers, the first sequence representing a pressed stack order, determines whether the pop-up sequence for the second order stack. All figures are not pushed onto the stack is assumed equal.

Such as the sequence order of 1,2,3,4,5 is pressed into a stack, is a pop-up sequence 4,5,3,2,1 sequence of the sequence corresponding to the stack, but it 4,3,5,1,2 the sequence can not be push pop-up sequence.

 

Problem-solving ideas


Using a press-pop stack to simulate operation.

import java.util.ArrayList;
import java.util.Stack;
public class Solution {

public boolean IsPopOrder(int[] pushSequence, int[] popSequence) {
    int n = pushSequence.length; Stack<Integer> stack = new Stack<>(); for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) { stack.push(pushSequence[pushIndex]); while (popIndex < n && !stack.isEmpty() && stack.peek() == popSequence[popIndex]) { stack.pop(); popIndex++; } } return stack.isEmpty(); }


}

 

Guess you like

Origin www.cnblogs.com/ziytong/p/12393100.html