码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer31题

时间:2017-08-12 00:38:26      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:scribe   stack   nbsp   blog   tac   for   class   pop   describe   

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
 
模拟一个入栈操作,每次匹配即可。不想解释太多。直接看代码吧
package com.algorithm04;

import java.util.Stack;

public class Algorithm31 {

	public static boolean IsPopOrder(int [] pushA,int [] popA) {
		Stack<Integer> stack = new Stack<Integer>();
		int i , j ;
		j = 0;
		if(pushA.length==0 || popA.length == 0 || pushA.length!=popA.length){
			return false;
		}
		for(i = 0 ; i< pushA.length ; i++){
			stack.push(pushA[i]);
			while(j < popA.length &&stack.peek()==popA[j]){
				stack.pop();
				j++;
			}
		}
		return stack.size()==0?true:false;
    }
	public static void main(String[] args) {
		int [] pushA = {1,2,3,4,5};
		int [] popA = {4,5,3,2,1};
 		System.err.println(IsPopOrder(pushA, popA));
	}
}

  

剑指offer31题

标签:scribe   stack   nbsp   blog   tac   for   class   pop   describe   

原文地址:http://www.cnblogs.com/CloudStrife/p/7348426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!