1.开始了堆栈的练习。
所谓的堆栈就是一种先进后出的数据结构,有点像堆盘子,越先进去的,越后出来。
这是个判断括号是否正确的问题。
链接:https://leetcode.com/problems/valid-parentheses/
20-valid-parentheses.png
我们使用list模拟stack(先进后出),append 入栈,pop出栈
这题的思路:
1.建立一个栈
2.建立一个键值对,key保存右括号.
3 数据不在key中,将数据压入栈
4 数据在key中,在栈顶查找key的value值
大致过程就是这样:
20-valid-parentheses.png
2.题解:
class Solution(object):
def isValid(self, s):
stack = []
pare_map = {')': '(',
'}': '{',
']': '['}
for c in s:
if c not in pare_map:
stack.append(c)
elif not stack or pare_map[c] != stack.pop(): # stack为空,或者不对应.
return False
return not stack
3.完整代码
查看链接:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/2-stack-quque/20-Valid-Parentheses.py








网友评论