LeetCode Everyday:坚持价值投资,做时间的朋友!!!
题目:
给定一个只包括'(',')','{','}','[',']'
的字符串,判断字符串是否有效。
有效字符串需满足:
1. 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例:
- 示例 1:
输入: "()" 输出: true
- 示例 2:
输入: "()[]{}" 输出: true
- 示例 3:
输入: "(]" 输出: false
- 示例 4:
输入: "([)]" 输出: false
- 示例 5:
输入: "{[]}" 输出: true
代码
方法一: 堆栈 题解
执行用时:32 ms, 在所有 Python3 提交中击败了97.36%的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了5.22%的用户
class Solution:
def isValid(self, s: str) -> bool:
dic = {')':'(',']':'[','}':'{'}
stack = []
for i in s:
if stack and i in dic:
if stack[-1] == dic[i]: stack.pop()
else: return False
else: stack.append(i)
return not stack
"""
For Example: input: s = "{[]}"
output: true
"""
s = "{[]}"
solution = Solution()
result = solution.isValid(s)
print('输出为:', result)
参考
- https://leetcode-cn.com/problems/valid-parentheses/solution/zhu-bu-fen-xi-tu-jie-zhan-zhan-shi-zui-biao-zhun-d/