题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
import java.util.*;
/*思路:先循环将pushA中的元素入栈,遍历的过程中检索popA可以pop的元素
**如果循环结束后栈还不空,则说明该序列不是pop序列。
**文字有点难说明白,看代码。
*/
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length==0||popA.length==0||pushA.length!=popA.length){
return false;
}
Stack<Integer> stack=new Stack<>();
int j=0;//popA的指针
for(int i=0;i<pushA.length;i++){
stack.push(pushA[i]);
while(!stack.isEmpty()&&stack.peek()==popA[j]){//检索popA可以pop的值
stack.pop();
j++;
}
}
return stack.isEmpty();
}
}