20.有效的括号
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-parentheses
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
lens = len(s)
if lens%2 == 1:
return False
result = []
ind = 0
result.append(s[0])
for i in range(1, lens):
if len(result) == 0:
result.append(s[i])
else:
if s[i]==')'and result[ind]=='(' or s[i]=='}' and result[ind]=='{' or s[i]==']' and result[ind]=='[':
result.pop(ind)
else:
result.append(s[i])
ind = max(0, len(result)-1)
if len(result) == 0:
return True
else:
return False