5 条题解
-
1
st=[""]*100 top=-1 flag=True s=input() for i in range(len(s)): if s[i]=="(" or s[i]=="[" or s[i]=="{": top+=1 st[top]=s[i] elif s[i]==")" and st[top]=="(" or s[i]=="]" and st[top]=="[" or s[i]=="}" and st[top]=="{": top-=1 else: flag=False break if top==-1 and flag: print('OK') else: print("Wrong")
-
1
Python 感谢C++大佬提供的思路
s = input() flag = True top1 = -1 top2 = -1 for ch in s: if ch == '(': top1 = top1 + 1 elif ch == ')': top1 = top1 - 1 if top1 < -1: flag = False elif ch == '[': top2 = top2 + 1 elif ch == ']': top2 = top2 - 1 if top2 < -1: flag = False for i in range(0, len(s) - 1): if s[i:i + 2] == '(]' or s[i:i + 2] == '[)': flag = False if top1 == -1 and top2 == -1 and flag: print("OK") else: print("Wrong")
-
1
这道题无非是两点需要注意的: 1.括号必须成双 2.括号不能有交叉
先来解决第一点:让括号配对 其实非常简单
#include<bits/stdc++.h> using namespace std; int main() { string n; cin >> n; int a1 = 0, a2 = 0, b1 = 0, b2 = 0; for(int i=0; i<=n.length(); i++){ if(n[i] == '(') a1++; if(n[i] == ')') a2++; if(n[i] == '[') b1++; if(n[i] == ']') b2++; } if(a1 == a2 and b1 == b2) cout << "OK"; else cout << "Wrong"; }
这样就让括号配对了。
第二点即不能有交叉 交叉的情况无非也就两种:
"(]" "[)"
所以我们就可以以此来改进代码:#include<bits/stdc++.h> using namespace std; int main() { string n; cin >> n; int a1 = 0, a2 = 0, b1 = 0, b2 = 0; for(int i=0; i<=n.length(); i++){ if((n[i] == '(' and n[i+1] == ']') or (n[i] == '[' and n[i+1] == ')')){ cout << "Wrong"; // 不满足直接输出 return 0; } if(n[i] == '(') a1++; if(n[i] == ')') a2++; if(n[i] == '[') b1++; if(n[i] == ']') b2++; } if(a1 == a2 and b1 == b2) cout<<"OK"; else cout << "Wrong"; return 0; }
-
0
骗分逃课
Python
内置exec()
方法可以直接使解释器运行字符串,我们直接运行输入的字符串,会产生以下结果:- 交叉: 编译器会返回
SyntaxError
- 某闭合括号后出现(): 如
[]()
,编译器会认为()
在调用方法,返回TypeError
,并且exec()
会发出string
警告SyntaxWarning
- []或()并列:
Python
没有对应语法,会返回SyntaxError
观察以上情况,情况1为错误,输出
Wrong
;情况2为正确,输出OK
;情况1为正确,应该输出
OK
,但是评测没有对应测试点,不然这道题还真不好解决了 👅Python
try: exec(input()) print("OK") except TypeError: print("OK") except SyntaxError: print("Wrong")
- 交叉: 编译器会返回
-
0
👀️
a=input() top=-1 s=[""]*255 for i in a: if i=='(': top+=1 s[top]=i if i=='[': top+=1 s[top]=i if i==')' or i==']': if top==-1: print('Wrong') top=-2 break if i==')': if s[top]=='(': top-=1 else: print('Wrong') top=-2 break if i==']': if s[top]=='[': top-=1 else: print('Wrong') top=-2 break if top>-1: print('Wrong') elif top==-1: print('OK')
- 1
信息
- ID
- 276
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 8
- 标签
- 递交数
- 1058
- 已通过
- 193
- 上传者