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

Solution 29: 合法的pop序列

时间:2015-07-10 12:42:08      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

问题描述

输入两个整数序列,其中一个为入栈序列,另一个为出栈序列。判断出栈序列是否是合法的。

 

解决思路

使用一个辅助栈,用最直观的方式。

 

程序

public class ValidPopSequence {
	public boolean isValidPopSeq(int[] push, int[] pop) {
		if (push == null && pop == null) {
			return true;
		}

		int i = 0, j = 0;
		Stack<Integer> s = new Stack<Integer>();

		while (j < pop.length) {
			while (i < push.length) {
				if (push[i] != pop[j]) {
					s.push(push[i]);
					++i;
				} else {
					// same, no push, pop next
					++i;
					++j;
					break;
				}
			}
			if (i == push.length) {
				// end push
				// check top of stack with pop
				if (s.isEmpty() || s.peek() != pop[j]) {
					return false;
				}
				s.pop();
				++j;
			}
		}
		
		return true;
	}
}

  

Solution 29: 合法的pop序列

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4635099.html

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