在给大家来一道算法题,很经典的算法题,希望大家从这个算法题中能学到更多东西,以及逻辑上的东西,喜欢的小伙伴点赞收藏
def isValid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
# 测试
s = "()[]{}"
if isValid(s):
print("字符串有效")
else:
print("字符串无效")