|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
原帖地址:https://fishc.com.cn/thread-167926-1-1.html
题目要求:输入测试字符串,检测括号匹配是否合法。
以下是小古比鱼编写的代码,感觉比小甲鱼老师提供的参考答案更简洁、更优雅,还可适用于包含非括号字符的情况!望各位鱼友走过路过,留下宝贵意见,共同交流进步!
- match = []
- brackets = input("请输入测试字符串:")
- for b in brackets:
- if b in ['(','[','{']:
- match.append(b) # 填入数据
- continue
- if b == ')' and match and match.pop() == '(' or \
- b == ']' and match and match.pop() == '[' or \
- b == '}' and match and match.pop() == '{':
- continue # 合法情况
- match.append('Error') # 非法情况
- break
- print("非法T_T" if match else "合法^o^")
复制代码 |
|