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;
}