力扣(LeetCode 20)有效的括号 python
2019-06-27 21:11
246 查看
题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
用栈模拟即可。
代码
class Solution: def isValid(self, s: str) -> bool: stact=[] for i in s: if i =='(' or i=='{' or i=='[': stact.append(i) else: if i==')' and stact and stact[-1]=='(': stact.pop() elif i=='}' and stact and stact[-1]=='{': stact.pop() elif i==']' and stact and stact[-1]=='[': stact.pop() else: return False if stact: return False return True
相关文章推荐
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- LeetCode题解(python)-20. 有效的括号
- Leetcode做题日记:20. 有效的括号 (PYTHON)
- Python LeetCode(20.有效的括号)
- [算法Rust,Go,Python,JS实现)]LeetCode之20-有效括号匹配
- Leetcode20 python有效的括号
- LeetCode刷题笔记 [20] 有效的括号
- python实现leetcode-第20题-有效的括号
- LeetCode 20. Valid Parentheses--验证括号是否有效
- LeetCode 20 Valid Parentheses(有效的括号)
- LeetCode 20. 有效的括号(java)
- Leetcode(20)有效的括号
- 【刷算法】LeetCode.20-有效的括号
- leetcode 括号组合题目 20 是否是有效括号 32 最大有效括号 301 去掉无效括号
- LeetCode - 20. 有效的括号
- leetcode刷题python之有效的括号
- leetcode_20.有效对括号(有问题)
- Leetcode:20 有效的括号
- Leetcode 20: 有效的括号(Valid Parentheses)
- leetcode题解-20.有效的括号