/**
*
* 中心思想: 遍历弹出序列,
* 每一个都先与两个栈额栈顶元素比较,有的话就弹出,遍历弹出序列的下一个元素
* 没有的话,就让压入序列继续压入help栈,当遇到目标元素时停下,然后越过该元素继续遍历弹出序列,
* 如果没遇到该元素说明弹出序列是错的直接返回
*/
public class Test extends People<Test>{
public static void main(String[] args) {
test1();
test2();
test3();
test4();
test5();
}
static void test1() {
int[] pushSequence = {4,5,3,1,2};
int[] popSequence = {2,1,3,5,4};
System.out.println(verify(pushSequence, popSequence));
}
static void test2() {
int[] pushSequence = {4,5,3,1,2};
int[] popSequence = {4,5,3,2,1};
System.out.println(verify(pushSequence, popSequence));
}
static void test3() {
int[] pushSequence = {3,4,5};
int[] popSequence = {4,5,3};
System.out.println(verify(pushSequence, popSequence));
}
static void test4() {
int[] pushSequence = {3,4,5,1,2};
int[] popSequence = {5,4,2,1,3};
System.out.println(verify(pushSequence, popSequence));
}
static void test5() {
int[] pushSequence = {1,2,3,4,5};
int[] popSequence = {4,3,5,1,2};
System.out.println(verify(pushSequence, popSequence));
}
public static boolean verify(int[] pushSequence, int[] popSequence) {
if (pushSequence == null || pushSequence.length < 1 ||
popSequence == null || popSequence.length < 1 || popSequence.length != pushSequence.length) {
return false;
}
Stack<Integer> help = new Stack<>();
int push = 0;
int pop = 0;
for (; pop < popSequence.length; pop++) {
if( !help.isEmpty() && help.peek() == popSequence[pop]) {
help.pop();
}else {
for (;push < pushSequence.length && pushSequence[push] != popSequence[pop]; push++) {
help.push(pushSequence[push]);
}
if (push == pushSequence.length) {
return false;
}
push++;
}
}
return true;
}
}
栈的压入,弹出序列java
最新推荐文章于 2023-02-20 09:12:06 发布