Pop Sequence

本文探讨如何使用栈的数据结构解决一个实际问题:给定最大容量M和数字顺序N,判断是否能通过随机弹出生成给定的序列。解法利用了栈的特性与中缀表达式转后缀表达式的思路。

前言

线性结构----栈


一、题目

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

链接:https://pintia.cn/problem-sets/1340842164139356160/problems/1368396163593801731

二、解法

与MOOC课程堆栈一节中示例:中缀表达式转后缀表达式的思想很相似。
对于给定的数N,可以生成1-N 的一个序列order,并附一个指针ord,对于输出顺序的数组M,也可附一个指针index,创建一个有容量的栈,对于M[index],若与栈顶的数字相同,则栈顶数字弹出,index+=1,若不等,则将order[ord]压入栈(如果栈还有容量并且ord未出order的界),否则break。

# 定义一个有容量的栈,功能只需要有添加和删除即可,栈顶数字用items[-1]来访问
class Stack():
    def __init__(self,size):
        self.items = []
        self.maxsize = size
    def push(self,items):
        if len(self.items) < self.maxsize:
            self.items.append(items)
    def pop(self):
        if len(self.items) > 0 :
            return self.items.pop()
# 接收参数            
maxsize,length,number = map(int,input().split())
# 生成序列order
order = [_ for _ in range(1,length+1)]
# 遍历输入的M
for _ in range(number):
    sample =  list(map(int,input().split()))
    # 实例化指定容量的栈 初始化指针
    stack = Stack(maxsize)
    index = 0
    ord = 0
    while index < len(sample) :
        if len(stack.items) :
            if stack.items[-1] != sample[index] :
            	# 防止ord出界
                if ord < length:
                    stack.push(order[ord])
                    ord += 1
                else:
                    break
            else:
                stack.pop()
                index += 1
        else: 
            stack.push(order[ord])
            ord += 1

    if index == len(sample):
        print("YES")
    else:
        print("NO")
    

在这里插入图片描述
雨停了,去跑步🏃‍🏃‍🏃‍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值