# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid.
# An input string is valid if: Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
import re
def isValid(s: str) -> bool:
if (s == ''):
return True
elif not ((s.count('(') - s.count(')')) == 0 and (s.count('[') - s.count(']')) == 0 and (s.count('{') - s.count('}')) == 0):
return False
else:
_result = [re.search(pattern, s)
for pattern in ['\((.)*\)', '\[(.)*\]', '\{(.)*\}']]
_result = ['' if _result[i] is None else _result[i].group()[1:-1]
for i in range(len(_result))]
return isValid(_result[0]) and isValid(_result[1]) and isValid(_result[2])
if __name__ == '__main__':
print(isValid('([]){'))
print(isValid('[]'))
print(isValid('(]'))
print(isValid('([)]'))
print(isValid('{[]}'))
print(isValid('({()}{[}])'))
5条答案
按热度按时间vxbzzdmp1#
不是最简短的答案,而是一个可读的:
nfeuvbwi2#
下面是dart中两种不同的解决方案:
vuktfyat3#
我想这会对你有帮助
vohkndzv4#
您可以检查this,但它是用python编写的
r8xiu3jd5#