1071:括号匹配

1071:括号匹配

Time/Memory Limit:1000 MS/32768 K 
Submitted: 818 Accepted: 176

 Problem Description

给个字符串,判断里面的左括号的数量是否等于右括号.

 Input

输入数据有多组,每组一个字符串(长度小于200),里面可能包含的括号有:{}[]()

 Output

每组数据的输出有一行,形式:Case x: 括号匹配(或者括号不匹配)
x表示第几个数据,默认出1开始,具体参见样例。

 Sample Input

{}
{

 Sample Output

Case 1:Yes.
Case 2:No!

 Hints

匹配类似于数学中的算式

例如:

{[()()]()}算匹配

[][{][}][]不算匹配
#include <iostream>
#include <stack>
using namespace std;
 
// 判断字符是不是左括号类型
bool isLeft(char c)
{
	return (c == '(' || c == '[' || c == '{');
}
 
// 判断右括号与左括号是否匹配
bool isMatch(char right, char left)
{
	if (right == ')')
	{
		return (left == '(');
	}
 
	if (right == ']')
	{
		return (left == '[');
	}
 
	if (right == '}')
	{
		return (left == '{');
	}
}
 
// 判断字符串是否匹配
bool matching(char* s)
{
	stack<char> cs;
	char c;
	while (*s)
	{
		c = *s;
		if (isLeft(c))
		{
			cs.push(c);
		}
		else
		{
			if (cs.empty() || !isMatch(c, cs.top()))
			{
				return false;
			}
 
			cs.pop();
		}
		++s;
	}
 
	if (!cs.empty())
	{
		return false;
	}
	return true;
}
int main()
{    int x=0;
	char s[200];
	while(cin>>s)
	{
	x++;
	if (matching(s))
	{
		cout <<"Case "<<x<<":Yes.";
	}
	else
	{
		cout<<"Case "<<x<<":No!";
	}
	cout<<endl;
 }
	return 0;
}

 

 

书上的一段代码,不过我没有弄会。

#include<iostream>
#include<string.h>
using namespace std;
/*括号匹配算法*/ 
int Prool(int n,char A[])
{
	 char S[50];
   int 	top=-1,i=0,flag=1;
   while(i<n&&flag)
   {
	   if(A[i]=='('||A[i]=='['||A[i]=='{')    S[++top]=A[i++];
   	else{
   		switch (A[i])
   		{
   		    case')':if(top=-1||S[top--]!='(')	flag=0;break;
   		    case']':if(top=-1||S[top--]!=']')	flag=0;break;
   		    case'}':if(top=-1||S[top--]!='{')	flag=0;break;
		}
	   }
	   i++;
   }
   return flag;
}
int main(){
	char A[200];int n;
	while(cin>>n>>A){
	cout<<Prool(n,A)<<endl;
	}
	
	
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

以码平川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值