The sword refers to offer--22. The push and pop sequence of the stack

Question: Input two integer sequences, the first sequence represents the push sequence of the stack, please judge whether the second sequence is the pop-up sequence of the stack. Assume that all numbers pushed onto the stack are not equal. eg: push={1,2,3,4,5} is the push sequence of a stack, pop={4,5,3,2,1} is one of its popup sequences

Analysis: Build an auxiliary stack and find the rule: If the next popped number happens to be the number on the top of the stack, then pop it directly. If the next popped number is not on the top of the stack, we push the number that has not been pushed into the stack sequence. Auxiliary stack until the next number that needs to be popped is pushed onto the top of the stack. If all numbers are pushed onto the stack and the next popped number is not found, then the sequence cannot be a popped sequence

import java.util. *;
public class wr22isPopOrder {
	public static boolean isPopOrder(int []push,int []pop){
		if(push.length==0 || pop.length==0){
			return false;
		}
		Stack<Integer> s=new Stack<>();
		int popIndex=0;//Position of popup sequence
		for(int i=0;i<push.length;i++){
			s.push(push[i]);
			while(!s.empty() && s.peek()==pop[popIndex]){
				s.pop();
				popIndex++;
			}
		}
		return s.empty();
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int []push={1,2,3,4,5};
		int []pop={4,5,3,2,1};
		int []pop2={4,3,5,1,2};
		System.out.println(isPopOrder(push,pop));
		System.out.println(isPopOrder(push,pop2));
	}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325569114&siteId=291194637