题目:
给定一个只包括
‘(’,’)’,’{’,’}’,’[’,’]’
的字符串,判断字符串是否有效。
有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串
示例1:
输入: "()"
输出: true
示例2:
输入: "()[]{}"
输出: true
示例3:
输入: "(]"
输出: false
示例4:
输入: "([)]"
输出: false
示例5:
输入: "{[]}"
输出: true
算法实现:
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
each = 0
while abs(each) < len(s) - 1:
if s[each] == '(' and s[each + 1] == ')':
s = s[:each] + s[each + 2:]
each -= 2
elif s[each] == '{' and s[each + 1] == '}':
s = s[:each] + s[each + 2:]
each -= 2
elif s[each] == '[' and s[each + 1] == ']':
s= s[:each] + s[each + 2:]
each -= 2
each = each + 1 if each >= 0 else 0
if s:
return False
else:
return True
思路:
此算法通过不断消去成对括号来实现判断括号是否有效
例如’{[()]}’
首先消去内部的’()‘变为’{[]}’
然后消去’[]‘变为’{}’
最后消去’{}’
当s为空串时,括号即为有效