您的位置:首页 > 其它

字符串匹配问题

2017-03-27 20:12 211 查看
、字符串匹配问题
【问题描述】
字符串中只含有括号 (),[],<>,{},判断输入的字符串中括号是否匹配。如果括号有互相包含的形式,从内到外必须是<>,(),[],{},例如。输入: [()] 输出:YES,而输入([]), ([])都应该输出NO。
【输入格式】strs.in
文件的第一行为一个整数n,表示以下有多少个由括好组成的字符串。接下来的n行,每行都是一个由括号组成的长度不超过255的字符串。
【输出格式】strs.out
在输出文件中有N行,每行都是YES或NO。
【输入样例】
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
><}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
【输出标例】
YES
YES
YES
YES
NO

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char c[10000001];
int topa=0;
int topb=0;
int topc=0;
int topd=0;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int flag=1;
scanf("%s",&c);
for(int i=0;i<=strlen(c)-1;i++)
{
if(c[i]=='(')
topa++;
else if(c[i]=='[')
topb++;
else if(c[i]=='{')
topc++;
else if(c[i]=='<')
topd++;
else if(c[i]==')')
{
if(topa>0)
topa--;
else
{
cout<<"NO"<<endl;
flag=0;
break;
}
}
else if(c[i]==']')
{
if(topb>0)
topb--;
else
{
cout<<"NO"<<endl;
flag=0;
break;
}
}
else if(c[i]=='}')
{
if(topc>0)
topc--;
else
{
cout<<"NO"<<endl;
flag=0;
break;
}
}
else if(c[i]=='>')
{
if(topd>0)
topd--;
else
{
cout<<"NO"<<endl;
flag=0;
break;
}
}
}
if(flag==1)
{
if(topa==0&&topb==0&&topc==0&&topd==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: