题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
[1,2,3,4,5],[4,3,5,1,2]
思路是维护一个栈,查看栈顶元素跟弹出序列是否一致,如果一致就出栈,否则就继续入栈。
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack();
int j = 0;
for (int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while (!stack.isEmpty() && j < popA.length && stack.peek() == popA[j]) {
stack.pop();
j++;
}
}
return stack.isEmpty() && j == popA.length;
}
}
查看1道真题和解析

