|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
请各位大佬帮我看看我的代码
为啥运行不了
我觉得逻辑上应该没问题诶
题目:请编写一个程序,判断给定的字符串 s 中括号的写法是否合法。
条件:
字符串仅包含 '('、')'、'['、']'、'{'、'}' 这三对括号的组合
左右括号必须成对编写,比如 "()" 是合法的,"(" 则是非法的
左右括号必须以正确的顺序闭合,比如 "{()}" 是合法的,"{(})" 则是非法的
我写的代码:
s = input("请输入测试字符串:")
list1 =[]
list2 =[]
for c in s:
if c == '(' or c== '{' or c == '[':
list1.append(c)
else:
list2.insert(0,c)
a = len(list1)
b = len(list2)
if a == b:
for i in range(0,a):
if list1[i] == '(' and list2[i] == ')':
continue
elif list1[i] == '{' and list2[i] == '}':
continue
elif list1[i] == '[' and list2[i] == ']':
continue
else:
print("不合法")
i = -1
break
if i == a:
print("合法")
else:
print("不合法")
本帖最后由 代码小白liu 于 2022-4-17 10:43 编辑
- s = input("请输入测试字符串:")
- list1 =[]
- list2 =[]
- for c in s:
- if c == '(' or c== '{' or c == '[':
- list1.append(c)
- else:
- list2.insert(0,c)
- a = len(list1)
- b = len(list2)
- if a == b:
- for i in range(0, a):
- if list1[i] == '(' and list2[i] == ')':
- continue
- elif list1[i] == '{' and list2[i] == '}':
- continue
- elif list1[i] == '[' and list2[i] == ']':
- continue
- else:
- print("不合法")
- break
- else:
- print("合法")
- else:
- print("不合法")
复制代码
修改了下代码能正常运行了,但是这个思路是只用于只有一种括号,如果是多种括号或者是嵌套的 就是不适用了,[{}] list1[0]是不等于list2[0]的
|
|