剑指Offer: (Java实现) 栈的压入、弹出序列
2017-05-28 19:56
295 查看
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列。假设压入栈的所有数字均不相等。例如压栈序列为 1、2、3、4、5.序列 4、5、3、2、1 是压栈序列对应的一个弹出序列,但 4、3、5、1、2 却不是。
分析:学过数据结构的人都知道,这种判断是考试中必考的。现在用Java语言实现,无非就是将逻辑转化为代码。假设大家知道 某个序列能否从特定的入栈顺序的组成的栈中弹出的规则。
分析:学过数据结构的人都知道,这种判断是考试中必考的。现在用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; } }
相关文章推荐
- 剑指offer刷题之java实现的栈的压入、弹出序列
- 剑指Offer:面试题22——栈的压入,弹出序列(java实现)
- 剑指offer--面试题22:栈的压入、弹出序列--Java实现
- 【剑指offer】栈的压入、弹出序列(java版)
- 剑指Offer-面试题22 栈的压入、弹出序列(python实现)
- 【剑指offer-Java版】22栈的压入弹出序列
- 剑指Offer:栈的压入、弹出序列(JAVA)
- 剑指offer第二十一题【栈的压入、弹出序列】c++实现
- 剑指Offer面试题22(Java版):栈的压入、弹出序列
- 剑指offer: 栈的压入、弹出序列
- 剑指offer:栈的压入、弹出序列
- 【剑指offer】面试题31:栈的压入、弹出序列
- 剑指 offer set 10 栈的压入、弹出序列
- 【剑指offer】面试题22:栈的压入、弹出序列
- 【面试题】剑指Offer-22-栈的压入和弹出序列
- 剑指offer----翻转单词顺序列----java实现
- 剑指offer--栈的压入、弹出序列
- 剑指offer-第四章解决面试题的思路(栈的压入和弹出序列)
- 剑指offer 之 栈的压入、弹出序列是否对应
- 【剑指Offer面试编程题】题目1366:栈的压入、弹出序列--九度OJ