C++ Python 合法的出栈序列

**

以下为C++版本

**
已知从1至n的数字序列,按顺序入栈,每个数字入栈后即可出栈,也可在栈中停留,等待后面的数字入栈出栈后,该数字再出栈,求该数字序列是否合法?

#include 
#include
bool check_is_valid_order(std::queue<int>& order)
{
     
 std::stack<int> S;
 int n = order.size();
 for (int i = 1; i <= n; i++)
 {
     
  S.push(i);
  while (!S.empty() && order.front() == S.top())  
  //只要S不空且队列头部与栈顶相同,即弹出元素
  {
     
   S.pop();
   order.pop();
  }
 }
 if (!S.empty())
 //如果最终栈不空,则说明序列不合法。
 {
     
  return false;
 }
 return true;
}

将入栈元素按入栈顺序由1到n进行编号,凡是合法的出栈序列,每个数后面的比它小的数,必然是按递减次序排列的。但该方法的代码量比较大。

**

以下为Python版本

**
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该站的弹出顺序。假设压入栈的所有数字均不相等。例如1,2,3,4,5是某栈的压入书序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        if not pushV or len(pushV) != len(popV):
            return False
        stack = []
        index = 0
        for item in pushV:
            stack.append(item)
            while stack and stack[-1] == popV[index]:
                stack.pop();
                index += 1

        if not stack:
            return True
        else:
            return False


if __name__ == '__main__':
    pushV = [1, 2, 3, 4, 5]
    popV1 = [4, 5, 3, 2, 1]
    popV2 = [4, 3, 5, 1, 2]
    s = Solution()
    print(s.IsPopOrder(pushV, popV1))
    print(s.IsPopOrder(pushV, popV2))

运行结果为:

True
False

你可能感兴趣的:(算法,出栈序列,顺序)