输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def IsPopOrder(self, pushV, popV): 4 n = len(pushV) 5 stack = [] 6 popout = [0] * n 7 preidx = 0 8 for i in range(len(pushV)): 9 cur = popV[i] 10 if pushV.count(cur) > 0: 11 idx = pushV.index(cur) 12 if idx >= preidx: 13 for j in range(preidx,idx): 14 if popout[j] == 1: 15 continue 16 else: 17 stack.append(pushV[j]) 18 else: 19 top = stack.pop(-1) 20 if top != cur: 21 return False 22 popout[idx] = 1 23 preidx = idx 24 else: 25 return False 26 return True 27 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 public boolean validateStackSequences(int[] pushed, int[] popped) { 3 int i = 0;//pushed数组的游标 4 int m = pushed.length; 5 int n = popped.length; 6 if(n == 0) { 7 return true;//空队列,直接返回true 8 } 9 Stack<Integer> st = new Stack<Integer>(); 10 st.push(-1); 11 for(int j=0;j<n;j++) { 12 while(st.peek() != popped[j] && i<m) { 13 st.push(pushed[i]); 14 i++; 15 } 16 if(st.peek() == popped[j]) { 17 st.pop(); 18 }else { 19 return false; 20 } 21 } 22 return st.size() == 1 && st.peek() == -1; 23 } 24 }