给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
栈的思路:遇见左括号进站,遇见右括号就弹出左括号进行匹配,最后栈为空就行
class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if c in '([{': stack.append(c) else: if not stack: return False temp = stack.pop() if c == ')': if temp != '(': return False if c == ']': if temp != '[': return False if c == '}': if temp != '{': return False return stack == [] 作者:jue-qiang-zha-zha 链接:https://leetcode-cn.com/problems/valid-parentheses/solution/20-you-xiao-de-gua-hao-zhan-by-jue-qiang-st97/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
投机取巧:
class Solution: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == ''