前言
线性结构----栈
一、题目
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")

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

被折叠的 条评论
为什么被折叠?



