堆栈又称为栈或堆叠,是计算机科学中一种特殊的串列形式的抽象数据类型,其特殊之处在于只能允许在链表或数组的一端进行加入数据(push)和输出数据(pop)的运算。由于堆栈数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。
isempty(self) 堆栈是否为空
size(self) 返回堆栈大小
push(self,item) 向堆栈压入元素
pop(self) 从堆栈弹出元素
peek(self) 返回栈顶元素
__str__(self) 输出堆栈元素
简单应用:括号匹配问题
给定一个字符串,其中的字符只包含四种括号:花括号{ }、中括号[ ]、圆括号( )、引号'',即它仅由( ) [ ] { }''这八个字符组成。
设计算法,判断该字符串是否有效,即字符串中括号是否匹配。
括号匹配要求括号必须以正确的顺序配对,如{ [ ] ( ) }或[ ( { } [ ] ) ]等为正确的格式,而[ ( ] )或{ [ ( ) }或( { } ] )均为不正确的格式。
单引号因为左右符号是相同的,所以对左右判断是无效的,单独进行算法匹配
代码如下:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# _ooOoo_
# o8888888o
# 88" . "88
# ( | - _ - | )
# O\ = /O
# ____/`---'\____
# .' \\| |// `.
# / \\|||:|||// \
# / _|||||-:- |||||- \
# | | \\\ - /// | |
# | \_| ''\---/'' | _/ |
# \ .-\__ `-` ___/-. /
# ___`. .' /--.--\ `. . __
# ."" '< `.___\_<|>_/___.' >'"".
# | | : `- \`.;`\ _ /`;.`/ - ` : | |
# \ \ `-. \_ __\ /__ _/ .-` / /
# ==`-.____`-.___\_____/___.-`____.-'==
# `=---='
'''
@Project :pythonalgorithms
@File :stackdatastructure.py
@Author :不胜人生一场醉
@Date :2021/7/15 16:07
'''
class Stack(object):
# 堆栈初始化
def __init__(self):
# 用list存储栈元素
self.items = []
# 判断是否为空
def isempty(self):
return self.items == []
# 加入元素
def push(self, item):
self.items.append(item)
# 弹出元素
def pop(self):
if self.items == []:
raise IndexError("Stack top is not exist!")
return self.items.pop()
# 返回栈顶元素
def peek(self):
if self.items == []:
raise IndexError("Stack top is not exist!")
return self.items[- 1]
# 返回栈的大小
def size(self):
return len(self.items)
def __str__(self):
return str(self.items)
def check_flag(text):
stack = Stack()
left_flag = "([{<"
right_flag = ")]}>"
flags = {")": "(", "]": "[", "}": "{", ">": "<"}
for i in text:
# 左右都是成对出现的,但'需要特殊判断
if i in ["'"] and stack.peek() not in ["'"]:
stack.push(i)
elif i in ["'"] and stack.peek() in ["'"]:
stack.pop()
return True
# 如果为左边的符号,则把左边的符号放到堆栈中
if i in left_flag:
stack.push(i)
# 如果为右边的符号
elif i in right_flag:
# 如果堆栈为空,返回False
if stack.isempty():
return False
# 如堆栈弹出值不为右边符号的字典值,返回False
if flags[i] != stack.pop():
return False
# 堆栈为空,则表示全部消费完成,所以为True
if stack.isempty():
return True
return False
if __name__ == "__main__":
stack = Stack()
# print(stack.pop())
# IndexError: Stack top is not exist!
stack.push("hello")
stack.push("world")
stack.push("helloworld")
print(stack)
print(stack.size())
print(stack.peek())
print(stack.pop())
print(stack.pop())
print(stack.pop())
# 一个基于堆栈的样例
print(check_flag("['d']"))
print(check_flag("[{12()3<dd>'d'2}]"))
print(check_flag("[{12(32})]"))
print(check_flag("[{12'32}']"))
输出结果为:
C:\python\pyproject\pythonalgorithms\venv\Scripts\python.exe C:/python/pyproject/pythonalgorithms/stackdatastructure.py
['hello', 'world', 'helloworld']
3
helloworld
helloworld
world
hello
True
True
False
False
以下为堆栈的简单示意图

本文分享自 python与大数据分析 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!