Validate Stack Sequences
Problem description:
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack. pushed is a permutation of popped. This is leetcode problem 946.
Two given parameters, pushed and popped array, describe the order of push and pop. Our task is to verify such an order is possible. My approach is to store the popped sequence into a queue. Push element into the stack based on pushed array, when the stack top is equal to queue head, pop the stack and poll the queue until stack is empty or the top element is different. Finally check whether stack is empty.
public boolean validateStackSequences(int[] pushed, int[] popped) { Queue<Integer> q=new LinkedList<Integer>(); Stack<Integer> s=new Stack<Integer>(); for(int i=0;i<popped.length;i++)q.offer(popped[i]); for(int i=0;i<pushed.length;i++){ s.push(pushed[i]); while(!s.empty() && s.peek().intValue()==q.peek().intValue()){ s.pop(); q.poll(); } } return s.empty(); }

浙公网安备 33010602011771号