括号匹配
(File IO): input:check.in
output:check.out
题目描述
假设表达式中允许包含圆括号和方括号两种括号,其嵌套的顺序随意,如([]())或[([][])]等为正确的匹配,[(])或([]()或(()))均为错误的匹配。
本题的任务是检验一个给定表达式中的括号是否正确匹配。
输入一个只包含圆括号和方括号的字符串,判断字符串中的括号是否匹配,匹配就输出“OK”,不匹配就输出“Wrong”。
输入
一行字符,只含有圆括号和方括号,个数小于 255。
输出
匹配就输出一行文本OK
,不匹配就输出一行文本Wrong
。
样例输入
[(])
样例输出
Wrong
最开始
658 bytes
#include<iostream>
#include<cstdio>
using namespace std;
char a[1001];
int s[1001],top,i=-1;
int main()
{
freopen("check.in","r",stdin);
freopen("check.out","w",stdout);
scanf("%s",a);
while(a[++i]=='(' || a[i]=='[' || a[i]==')' || a[i]==']')
{
if(a[i]=='(')
s[++top]=1;
else if(a[i]=='[')
s[++top]=2;
else if(a[i]==')')
{
if(top==0 || s[top]==2)
{
cout<<"Wrong";
return 0;
}
else
s[top--]=0;
}
else if(a[i]==']')
{
if(top==0 || s[top]==1)
{
cout<<"Wrong";
return 0;
}
else
s[top--]=0;
}
}
if(top==0)
cout<<"OK";
else
cout<<"Wrong";
fclose(stdin);fclose(stdout);
return 0;
}
缩短后
371 bytes
😃
#include<cstdio>
#include<cstring>
main(){
freopen("check.in","r",stdin);
freopen("check.out","w",stdout);
char s[1000];
scanf("%s",s+1);
if(strlen(s+1)%2==1){
printf("Wrong");
return 0;
}
for(int i=1;i<strlen(s+1);i++){
if(s[i]=='['&&s[i+1]==')'||s[i]=='('&&s[i+1]==']'){
printf("Wrong");
return 0;
}
}
printf("OK");
}
nice~~