剑指offer 22. 栈的压入、弹出序列
2017-05-09 16:38
281 查看
// 题目:输入两个整型数组,判断第二个是不是第一个的栈输出序列 // 解法:使用队列完成,输出传入栈中再输出 public class Main { public static void main(String[] args) { System.out.println(isSeq(new int[] { 1, 2,3,4,5 }, new int[] {4,5,3,2,1 })); } private static boolean isSeq(int[] input, int[] output) { if(input.length == 0 || input.length != output.length){ //如果长度不相等,直接false return false; } Stack<Integer> s = new Stack<Integer>(); //建立栈,模拟实际情况 int inputIndex = 0; int outputIndex = 0; while(outputIndex != output.length){ //如果输出队列没有遍历完 if(inputIndex == input.length && s.peek()!= output[outputIndex]){ //如果输入队列遍历完了且栈顶元素不为输入的当前元素就false return false; } while(s.isEmpty() || s.peek()!=output[outputIndex]){ //如果栈为空或栈顶元素不为输出队列的当前元素就将输入队列的元素入栈 s.push(input[inputIndex++]); if(inputIndex == input.length && s.peek()!= output[outputIndex]){ return false; } } s.pop(); //如果相同就出栈并检查输出序列的下一个元素 outputIndex++; } return true; } }
相关文章推荐
- 【剑指offer】数据结构 ——栈的压入、弹出序列(C++)
- 剑指Offer——(21)栈的压入、弹出序列
- 【剑指offer】栈的压入、弹出序列(java版)
- 【剑指offer 面试题22】栈的压入、弹出序列
- 【剑指offer】4.3举例让抽象问题具体化——面试题22:栈的压入、弹出序列
- (十四)剑指offer之栈的压入弹出序列及包含min函数的栈
- 剑指offer---桟的压入、弹出序列
- 【剑指offer】题22:栈的压入、弹出序列
- 剑指offer-栈的压入、弹出序列-php
- 【面试题】剑指Offer-22-栈的压入和弹出序列
- 剑指offer之栈的压入、弹出序列
- 剑指offer:栈的压入、弹出序列
- 剑指Offer:面试题22——栈的压入,弹出序列(java实现)
- 剑指offer——栈的压入、弹出序列____
- 剑指offer-面试题22-栈的压入、弹出序列
- 剑指 offer set 10 栈的压入、弹出序列
- 剑指offer 栈的压入、弹出序列
- 剑指offer 面试题22:栈的压入、弹出序列 题解
- 剑指offer面试题22:栈的压入、弹出序列
- 剑指offer 22 栈的压入、弹出序列