【Leetcode】【python】Valid Parentheses
来源:互联网 发布:python retry 编辑:程序博客网 时间:2024/05/01 07:26
题目大意
判断括号开闭
解题思路
栈
简单题,思路正确即可
代码
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for char in s: if char == '(' or char == '{' or char == '[': stack.append(char) continue elif char == ')': temp = '(' elif char == '}': temp = '{' elif char == ']': temp = '[' else: return False if stack: if stack[-1] == temp: stack.pop() else: return False else: return False if len(stack) != 0: return False return True
由于pop()时会输出pop的数值,所以可以简化:
class Solution: # @return a boolean def isValid(self, s): stack = [] for i in range(len(s)): if s[i] == '(' or s[i] == '[' or s[i] == '{': stack.append(s[i]) if s[i] == ')': if stack == [] or stack.pop() != '(': return False if s[i] == ']': if stack == [] or stack.pop() != '[': return False if s[i] == '}': if stack == [] or stack.pop() != '{': return False if stack: return False else: return True
总结
阅读全文
0 0
- Leetcode-Valid Parentheses-Python
- 【Leetcode】【python】Valid Parentheses
- 【LeetCode with Python】 Valid Parentheses
- 20. Valid Parentheses Leetcode Python
- leetcode 020 Valid Parentheses(Python)
- [leetcode:python]20.Valid Parentheses
- 【Leetcode】【python】Longest Valid Parentheses
- 【LeetCode 20】Valid Parentheses(Python)
- Python学习——leetcode(Valid Parentheses)
- leetcode 日经贴,python code -Valid Parentheses
- leetcode 日经贴,python code -Longest Valid Parentheses
- [Leetcode]32. Longest Valid Parentheses @python
- 【leetcode】20. Valid Parentheses(Python & C++)
- LeetCode: Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode: Valid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Valid Parentheses
- Orleans---持久化
- Spring Cloud Config
- gets()getchar()与缓冲区的问题
- 常见的安全算法
- 吃青春饭”的程序员们:再过 5 年,你还在写代码吗?
- 【Leetcode】【python】Valid Parentheses
- error C2275 : 'UNICODE_STRING' :illegal use of this type as an expression
- Nginx的启动和停止
- IOS 设置一个UIView里面的全部控件状态
- 欢迎使用CSDN-markdown编辑器
- oracle通过配置文件增加登录用户
- 发送短信消息
- Java
- 关于gitlab 9.1.2 (最新版)的安装、卸载及配置