offer31

tech2026-09-23  2

public class Main { public static void main(String[] args) { int[] pushed = {1,2,3,4,5}; int[] popped = {4,3,5,1,2}; Stack<Integer> st = new Stack(); int i = 0,j = 0,n = pushed.length; boolean f = true; while(j < n) {//取小的,因为前面循环内已经判断了i //可以在一个while内进行判断 if(i < n) {//先进行压栈操作 st.push(pushed[i]); //当栈顶元素等于当前的出栈数组中的元素时,则将栈顶元素弹出 while(!st.isEmpty() && j < n && st.peek() == popped[j]) { j++; st.pop(); } i++; }else { //如果最终栈中还有没有出栈的元素,则看剩余元素的出栈序列是否等于出栈数组序列 while(!st.isEmpty() && j < n) { if(st.pop() != popped[j++]) { f = false; break; } } } } System.out.println(f); } }

 

最新回复(0)