您的位置:首页 > 运维架构

Solution 29: 合法的pop序列

2015-07-10 10:45 169 查看
问题描述

输入两个整数序列,其中一个为入栈序列,另一个为出栈序列。判断出栈序列是否是合法的。

解决思路

使用一个辅助栈,用最直观的方式。

程序

public class ValidPopSequence {
public boolean isValidPopSeq(int[] push, int[] pop) {
if (push == null && pop == null) {
return true;
}

int i = 0, j = 0;
Stack<Integer> s = new Stack<Integer>();

while (j < pop.length) {
while (i < push.length) {
if (push[i] != pop[j]) {
s.push(push[i]);
++i;
} else {
// same, no push, pop next
++i;
++j;
break;
}
}
if (i == push.length) {
// end push
// check top of stack with pop
if (s.isEmpty() || s.peek() != pop[j]) {
return false;
}
s.pop();
++j;
}
}

return true;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: