AB2 栈的压入、弹出序列
描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
- 0<=pushV.length == popV.length <=1000
- -1000<=pushV[i]<=1000
- pushV 的所有数字均不相同
我的实现:
写的比较复杂,首先是自己定义了一个MyStack类;然后遍历pushA入栈,如果栈不为空且栈顶元素值与popA值相等,则出栈;最后,如果栈非空,如果有一个popA元素与栈顶元素不同,则返回false。
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
int n = popA.length;
MyStack myStack = new MyStack();
int j = 0;
for (int i = 0; i < n; i++) {
while (!myStack.isEmpty() && myStack.top() == popA[j]) {
j++;
myStack.pop();
}
myStack.push(pushA[i]);
}
while (!myStack.isEmpty()) {
if (myStack.top() == popA[j]) {
j++;
myStack.pop();
} else {
return false;
}
}
return true;
}
}
class MyStack {
private int n = 0;
private Node first;
private class Node {
int item;
Node next;
}
public boolean isEmpty() {
return n == 0;
}
public void push(int x) {
Node oldFirst = first;
first = new Node();
first.item = x;
first.next = oldFirst;
n++;
}
public int pop() {
int item = first.item;
first = first.next;
n--;
return item;
}
public int top() {
return first.item;
}
}
优化后:
遍历pushA数组,先入栈,如果栈非空且栈顶元素与popA值一致,则不断出栈。最后,如果栈为空,则返回true。
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
//辅助栈
Stack<Integer> stack = new Stack<>();
int j = 0;//popA数组的索引
for (int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while (!stack.empty() && stack.peek() == popA[j]) {
stack.pop();
j++;
}
}
return stack.empty();
}
}