棧的壓入、彈出序列

  • 輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否爲該棧的彈出順序。假設壓入棧的全部數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不多是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
	public boolean IsPopOrder(int[] pushA, int[] popA) {
		Stack<Integer> stack = new Stack<Integer>();
		int len = pushA.length;
		if (len == 0)
			return true;
		int curr;
		int index = 0;
		for (int i = 0; i < len; ++i) {
			curr = popA[i];
			while (stack.empty() || stack.peek() != curr) {
				if (index == len)
					return false;
				stack.push(pushA[index++]);
			}
			stack.pop();
		}
		return true;
	}
}
相關文章
相關標籤/搜索