解决这个问题很直观的想法是建立一个辅助栈,把输入的第一个序列中数字一次压入该辅助栈,并按照第二个序列的顺序一次从该栈中弹出数字。
总结上述入栈、出栈的过程。我们可以判断一个序列是不是栈的弹出序列的规律,如果下一个弹出的数字刚好是栈顶数字,那么直接弹出,如果下一个弹出的数字不在栈顶,则把亚展薛烈中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有数字都压入栈后仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
package question31_stack_list;
import java.util.Stack;
/**
* @Classname Solution
* @Description TODO
* @Date 2020/3/27 13:51
* @Created by mmz
*/
public class Solution {
public static boolean isPop(int[] pusha,int[] pushb){
if(pusha == null || pushb ==null){
return false;
}
Stack<Integer> stack = new Stack<>();
int j = 0;
for(int i =0;i<pusha.length;i++){
stack.push(pusha[i]);
while(!stack.isEmpty() &&stack.peek() == pushb[j]){
stack.pop();
j++;
}
}
return stack.isEmpty();
}
}
二刷
package question31_栈的压入弹出序列;
import java.util.Stack;
/**
* @Classname Main
* @Description TODO
* @Date 2020/4/11 23:16
* @Created by mmz
*/
public class Main {
static Stack<Integer> stack = new Stack<>();
static boolean Core(int[] arr1,int[] arr2){
int j = 0;
for(int i = 0;i<arr1.length;++i){
stack.push(arr1[i]);
while(!stack.isEmpty() && stack.peek() == arr2[j]){
stack.pop();
j++;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
int[] arr1 = new int[]{1,2,3,4,5};
int[] arr2 =new int[]{4,3,5,1,2};
System.out.println(Core(arr1, arr2));
}
}