检查Python栈中的元素是否成对排序


假设我们有一个数字栈;我们必须检查栈中的值是否成对连续。这些对可以是递增或递减的。如果栈有奇数个值,则顶部元素将被排除在对之外。并且我们应该在检查后保留原始栈内容。

为了解决这个问题,我们可以在栈上使用三个操作,称为push、pop和检查栈是否为空。

因此,如果输入类似于stk = [5, 6, -4, -5, 12, 11, 6, 7, 22],则输出将为True,因为在删除顶部元素22后,对为[(5, 6), (-4, -5), (12, 11), (6, 7)],所有这些都是连续的。

为了解决这个问题,我们将遵循以下步骤:

  • temp := 从stk中弹出元素并推入temp
  • 清空栈stk
  • flag := True
  • 当temp的大小> 1时,执行以下操作:
    • item_first, item_second := temp的顶部两个元素并弹出它们
    • 如果|item_first - item_second|不等于1,则
      • flag := False
    • 将item_first和item_second推入stk
  • 如果temp的大小等于1,则
    • 将temp的顶部推入stk
  • 返回flag

让我们看看下面的实现,以便更好地理解:

示例代码

在线演示

def solve(stk):
   temp = stk[::-1]
   stk.clear()
 
   flag = True
   while len(temp) > 1: 
      item_first = temp[-1] 
      temp.pop() 
      item_second = temp[-1] 
      temp.pop() 
      if abs(item_first - item_second) != 1: 
         flag = False
 
      stk.append(item_first) 
      stk.append(item_second)
 
    if len(temp) == 1: 
      stk.append(temp[-1]) 
 
   return flag
   
stk = [5, 6, -4, -5, 12, 11, 6, 7, 22]
print(solve(stk))

输入

[5, 6, -4, -5, 12, 11, 6, 7, 22]

输出

True

更新于: 2021年1月15日

245次浏览

开启你的职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.