Python3有效括号问题
生活随笔
收集整理的这篇文章主要介绍了
Python3有效括号问题
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
Python3有效括号问题
原题 https://leetcode-cn.com/problems/valid-parentheses/
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()" 输出: true示例 2:
输入: "()[]{}" 输出: true示例 3:
输入: "(]" 输出: false示例 4:
输入: "([)]" 输出: false示例 5:
输入: "{[]}" 输出: true解题:
class Solution:def isValid(self, s: str) -> bool:stack = [] # 只存未被配对的( [ { 遇到配对的直接出栈n = len(s)for i in range(n):w = s[i]if w == ')':length = len(stack)if length == 0 or stack[length - 1] != '(':return Falseelse:stack.pop()elif w == '}':length = len(stack)if length == 0 or stack[length - 1] != '{':return Falseelse:stack.pop()elif w == ']':length = len(stack)if length == 0 or stack[length - 1] != '[':return Falseelse:stack.pop()elif w == '(' or w == '{' or w == '[':stack.append(w)return len(stack) == 0 # 都配对了则栈为空 如果栈不为空则说明未配对总结
以上是生活随笔为你收集整理的Python3有效括号问题的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 嘴型有哪几种
- 下一篇: Python3最长连续递增序列问题