栈的压入、弹出序列
来源:互联网 发布:淘宝网上买红酒靠谱吗 编辑:程序博客网 时间:2024/06/06 07:21
Description: 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
import java.util.Stack; /** * @author Mengjun Li * @create 2017/10/3 * @since 1.0.0 */ public class IsPopOrder { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {3, 5, 4, 2, 1}; int[] arr3 = {4, 3, 5, 1, 2}; System.out.println(isPopOrder(arr1, arr2)); System.out.println(isPopOrder(arr1, arr3)); } /** * 引入stack来实现push中数组的出入栈。 * 时间复杂度O(n),空间复杂度O(n) */ public static boolean isPopOrder(int[] push, int[] pop) { Stack<Integer> tmp = new Stack<Integer>(); int j = 0, i = 0; for (; j < pop.length && i < pop.length; ) { if (push[j] == pop[i]) { j++; i++; } else tmp.push(push[j++]); } while (i < pop.length) if (pop[i++] != tmp.pop())//由于push和pop数组大小一致,所以这里不会出现tmp==null时再pop出栈的情形,否则需要放在try...catch..finally中实现 return false; return true; }}
**补充:当栈为空,即stack = null时
stack.pop会抛出异常EmptyStackException()。
JDK1.8中pop的实现如下:
public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; }
pop内部调用peek()方法:
public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); }
输出结果为:
true
false
阅读全文
0 0
- 1366栈的压入弹出序列
- 栈的压入、弹出序列
- 栈的压入、弹出序列
- 栈的压入、弹出序列
- Q22:栈的压入、弹出序列
- 栈的压入弹出序列
- 栈的压入、弹出序列
- 栈的压入弹出序列
- 栈的压入、弹出序列
- 栈的压入弹出序列
- 栈的压入、弹出序列
- 栈的压入、弹出序列
- 栈的压入弹出序列
- 栈的压入、弹出序列
- 栈的压入和弹出序列
- 栈的压入、弹出序列
- 栈的压入、弹出序列
- 栈的压入、弹出序列
- Java中Arrays.sort()实现
- 专治Python2.*编码
- 2017国庆郑州集训Day2
- eclipse中导入spring源码
- 343. Integer Break
- 栈的压入、弹出序列
- 汇编语法指令作用总结
- C++算法实现Bellman-Ford算法
- 回溯法简单示例
- poj2949 Word Rings(建图+二分答案+spfa判正环)
- 日期类型与常用工具类
- cuda8.0安装
- HIPHOP手势
- 在遍历中使用 iterator/reverse_iterator 进行 Erase 的用法