Leetcode20: Valid Parentheses
来源:互联网 发布:java防止表单重复提交 编辑:程序博客网 时间:2024/06/10 04:51
这题的答题思路基本是对了,用字典来解决,不过,还是没有对stack的应用太熟悉,还需练习。
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if len(s)%2 !=0: #如果元素个数是单数,直接枪毙 return False if not s: #如果是空字符串,返回True return True a={')':'(', '}':'{', ']':'['} #这题的关键,将结尾括号和开始括号一一对应起来,并且用结尾符号作为键 stack = [] #初始化一个列表,作为stack的结构 for i in s : #历遍s的每个元素 if i in '({[': #如果元素是开始括号的一种 stack.append(i) #把元素添加进stack elif i in ')}]': #如果是结尾符号 if not stack: #如果此时stack是空的,直接返回False,比如"[])"这种情况 return False elif stack and stack.pop() != a[i]: #如果stack非空,但是最后一个元素和当前元素再字典a里面取出的值不一样 return False #也返回False else: return False #如果i不在以上范围内,直接返回False if stack: #如果结束历遍以后,stack还是非空,返回False return False else: #如果历遍结束以后,stack为空,则返回True return True
0 0
- LeetCode20: Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode20-Valid Parentheses
- LeetCode20:Valid Parentheses
- LeetCode20:Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20 Valid Parentheses
- LeetCode20. Valid Parentheses
- Leetcode20: Valid Parentheses
- Leetcode20. Valid Parentheses
- leetcode20:Valid Parentheses
- LeetCode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 【LeetCode20】【Valid Parentheses】
- Leetcode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- nginx+php的配置与原理
- Linux c==Shell的管道及命令 (21)
- 认识html标签
- Atitit 发帖机实现(2)---usrQBN2243 文本解析到对象协议规范
- getch()、_sleep() 函数的正确用法
- Leetcode20: Valid Parentheses
- #Mac OS X下Maven部署
- Leetcode. 135 Candy(Hard)
- IE浏览器使用JS打印部分网页
- Atitit 发帖机实现(3 )---usrQBN023 js提交ajax内容到后端规范与标准化
- php ob系列的函数
- 初试Unity 3D——实例的创建与销毁
- JS-DHTML模型
- 操作系统---进程调度算法