题目描述
现在有一种只包括左右小括号(“(”和“)”)和空格(” “)的字符串序列,请你判断括号是否匹配,如果匹配就输出Yes,不匹配输出No。
输入
输入数据第一行输入一个T(0≤T≤100),表示测试数据的组数。
接下来有T行测试数据,每行有一个符合题意的字符串,字符串长度不超过500。
输出
每组测试数据,先输出一个”Case %d:“,%d表示第几组测试数据。接着,如果字符串括号匹配,输出Yes,否则,输出No。具体输出格式参考下面输出样例。
样例输入
2
( ())
)(
样例输出
Case 1:Yes
Case 2:No
示例代码
/*
[--91 ]--93
{--123 }--125
<--60 >--62
(--40 )--41
*/
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
#define maxsize 500
class mystack
{
public:
char data[maxsize+1];//栈
int top;//栈顶指针
mystack(){top=-1;}//栈为空
bool isEmpty(){return top<0? true: false;}//判断栈是否为空
bool isFull(){return top<maxsize-1? false: true;}//判断栈是否已满
void push(char x)//入栈
{
if(isFull())
return;
else
{
top++;//栈顶指针加一
data[top]=x;//数据如栈
}
}
bool pop(char &x)//出栈,并用x返回出栈的值
{
if(isEmpty())
return false;
else
{
x=data[top];//数据先出栈
top--;//栈顶指针减一
}
}
void clean(){top=-1;}//清空栈
char getTop(){if(!isEmpty())return data[top];else return '\0';}//返回栈顶元素
void create()//创建栈
{
//函数暂时保留
}
};
int main()
{
freopen("in.txt","r",stdin);
mystack s;//创建一个栈
int n;
cin>>n;
for(int i=-1;i<n;i++)
{
//char ch[maxsize];
string ch;
//char *ch;
//ch=new char[maxsize+1];
//cin.ignore(1024,'\n');
//cin.get(ch,501);
getline(cin,ch);//读取一行到字符数组中
if(i<0)continue;//屏蔽第一行
printf("Case %d:",i+1);
int j=0;
//cout<<ch<<endl;
if(ch[j]=='\0'||ch[j]=='@')cout<<"YES"<<endl;
if(ch[j]==']'||ch[j]=='}'||ch[j]==')'||ch[j]=='>')cout<<"NO"<<endl;
while(ch[j]!='\0'&&ch[j]!='@')
{
//左括号入栈
if(ch[j]=='['||ch[j]=='{'||ch[j]=='('||ch[j]=='<')
{
s.push(ch[j]);
j++;
continue;
}
//匹配右括号
char x=s.getTop();
if(ch[j]==']'||ch[j]=='}'||ch[j]=='>')
{
if(int(ch[j])-int(x)==2)
{
s.pop(x);
j++;continue;
}
}
if(ch[j]==')'&&x=='(')
{
s.pop(x);
j++;continue;
}
j++;
}
if(s.isEmpty())cout<<"YES"<<endl;
else cout<<"NO"<<endl;
s.clean();
}
return 0;
}