第一步非常简单。为了确定一系列步骤是否导致上溢或下溢,我们使用以下算法,其中 k 是堆栈的大小限制,指令列表是 PUSH 或 POP 列表:
在 Python 中:
def undeflows(lst):
count = 0
for x in lst:
if x == PUSH:
count += 1
else:
# We know that x == POP
if count == 0:
return True
count -= 1
return False
对于第二部分,关键是我们可以推断产生给定输出的操作顺序必须是什么。考虑以下算法:
在 Python 中:
def test_permutation(perm):
stack = []
next_to_read = 0
for val in perm:
if val >= next_to_read:
# in this case, we haven't pushed val yet. We'll need to push
# next_to_read to val inclusive, then pop val.
stack.extend(range(next_to_read, val))
next_to_read = val + 1
# Otherwise, we must have already pushed val. We must check to make sure
# we can pop it.
elif stack and stack[-1] == val:
stack.pop()
else:
return False
# at this point, stack should be empty.
return not stack
如果我们保证输入实际上是0、1、...、n-1的排列,那么我们可以修改代码为
def test_permutation(perm):
stack = []
next_to_read = 0
for val in perm:
if val >= next_to_read:
# in this case, we haven't pushed val yet. We'll need to push
# next_to_read to val inclusive, then pop val.
stack.extend(range(next_to_read, val))
next_to_read = val + 1
# Otherwise, we must have already pushed val. We must check to make sure
# we can pop it.
elif stack[-1] == val:
stack.pop()
else:
return False
# at this point, stack should be empty.
return True