剑指offer 22. 栈的压入、弹出序列

来源:互联网 发布:淘宝法院拍卖网 编辑:程序博客网 时间:2024/06/08 06:42
// 题目:输入两个整型数组,判断第二个是不是第一个的栈输出序列// 解法:使用队列完成,输出传入栈中再输出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){//如果长度不相等,直接falsereturn 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]){//如果输入队列遍历完了且栈顶元素不为输入的当前元素就falsereturn 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;}}

0 0
原创粉丝点击