您的位置:首页 > Web前端

剑指offer 22题 【举例让抽象具体化】栈的压入、弹出序列

2016-07-14 23:04 363 查看

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路很简单,将pushA不断压入栈中,如果栈顶与popA匹配,则pushA出栈,最后看栈是否为空

import java.util.*;

public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA == null || pushA.length == 0 || popA == null || popA.length == 0)
return false;
int indexPush =0,indexPop = 0;
Stack<Integer> stack = new Stack<Integer>();
while(indexPush < pushA.length ){
stack.add(pushA[indexPush++]);
while(!stack.empty() && stack.peek() == Integer.valueOf(popA[indexPop]) ){
stack.pop();
indexPop++;
}
}
if(stack.empty())
return true;
else
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: