括号匹配#最简短

括号匹配
(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~~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值