剑指Offer: (Java实现) 栈的压入、弹出序列
来源:互联网 发布:java入门到精通 4 pdf 编辑:程序博客网 时间:2024/06/05 02:09
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列。假设压入栈的所有数字均不相等。例如压栈序列为 1、2、3、4、5.序列 4、5、3、2、1 是压栈序列对应的一个弹出序列,但 4、3、5、1、2 却不是。
分析:学过数据结构的人都知道,这种判断是考试中必考的。现在用Java语言实现,无非就是将逻辑转化为代码。假设大家知道 某个序列能否从特定的入栈顺序的组成的栈中弹出的规则。
import java.util.Stack;/** * @author 作者 : shanzhi * @version 创建时间:2017-5-28 下午12:19:33 * 贡献点在于用Java来实现 */public class JZ22_StackInputOuput { public static int sL = 0; public static int oL = 0; public static void main(String[] args) { int[] source = {1,2,3,4,5}; int[] out1 = {4,5,3,2,1}; int[] out2 = {4,3,5,1,2}; sL = source.length; oL = out1.length; System.out.println(match(source,out1)); } public static boolean match(int[] source,int[] out){ int i = 0; Stack<Integer> sta = new Stack<Integer>(); int index1 = 0; //对应source的下标,用于获取具体值 int index2 = 0; //对应out的下标,用于获取具体值 while( index2 < oL){ int r1 = findIndex(source,out[index2]); if( r1 == sL){ break; }else if( r1 >= index1 ){ for ( i = index1;i <= r1;i++){ sta.push(source[i]); } index1 = i; sta.pop(); index2++; }else if( r1 < index1 ){ if( sta.peek() != out[index2]){ break; } else { sta.pop(); index2++; } } } if( index2 == oL ){ return true; } return false; } /** * 如果返回的是source数组的长度说明没找到。 */ public static int findIndex(int[] source, int num){ int i = 0; for( ; i< sL; i++){ if( source[i] == num){ break; } } return i; }}
阅读全文
0 0
- 剑指Offer: (Java实现) 栈的压入、弹出序列
- 剑指Offer:栈的压入、弹出序列(JAVA)
- 剑指offer:栈的压入、弹出序列(java)
- 剑指offer刷题之java实现的栈的压入、弹出序列
- 剑指offer--面试题22:栈的压入、弹出序列--Java实现
- 剑指Offer:面试题22——栈的压入,弹出序列(java实现)
- offer,栈的压入、弹出序列
- 【剑指offer】栈的压入弹出序列
- 剑指offer系列源码-栈的压入、弹出序列
- 剑指offer--栈的压入、弹出序列
- 剑指Offer之 - 栈的压入、弹出序列
- 剑指offer:栈的压入、弹出序列
- 《剑指offer》栈的压入、弹出序列
- 剑指Offer系列---(24)栈的压入、弹出序列
- 栈的压入、弹出序列(剑指offer)
- 剑指 offer:栈的压入、弹出序列
- 【剑指Offer】栈的压入、弹出序列
- 剑指offer—栈的压入、弹出序列
- 谈Android接入Sdk开发的安全性方案
- React进阶
- Thread.java
- (12)ffmpeg结构体分析:AVFrame
- 深入理解javascript原型和闭包(15)——闭包
- 剑指Offer: (Java实现) 栈的压入、弹出序列
- maven工程的结构
- 【vb.net】.net初体验
- USACO 牛的旅行 Cow Tours
- 简单ui效果实现,模仿腾讯体育点击全屏实现
- Facebook 面试题 | 岛的周长
- vim 查找统计一个字符串出现次数
- Intellij mac快捷键
- 模式识别和机器学习 笔记