標籤:os io 資料 for ar 問題 div 時間
括弧配對問題時間限制:3000 ms | 記憶體限制:65535 KB難度:3
-
描述
-
現在,有一行括弧序列,請你檢查這行括弧是否配對。
-
輸入
-
第一行輸入一個數N(0<N<=100),表示有N組測試資料。後面的N行輸入多組輸入資料,每組輸入資料都是一個字串S(S的長度小於10000,且S不是空串),測試資料群組數少於5組。資料保證S中只含有"[","]","(",")"四種字元
-
輸出
-
每組輸入資料的輸出佔一行,如果該字串中所含的括弧是配對的,則輸出Yes,如果不配對則輸出No
-
範例輸入
-
3[(])(])([[]()])
-
範例輸出
-
NoNoYes
#include<stdio.h>
#include<stack>
using namespace std;
stack< char >s;
bool mate(char a,char b)
{
return a==‘(‘&& b==‘)‘ || a==‘[‘&& b==‘]‘;
}
int main()
{
int T,i;char str[10010];
scanf("%d",&T);
getchar();
while(T--)
{
gets(str);
// puts(str);
while(!s.empty()) s.pop();
for(i=0;str[i]!=‘\0‘;i++)
{
if(s.empty() || !mate( s.top(),str[i]))
s.push(str[i]);
else s.pop();
}
if(s.empty())
printf("Yes\n");
else printf("No\n");
}
return 0;
}
#include<iostream>
using namespace std;
#include<stack>
#include<cstring>
#include<cmath>
int main()
{
stack<char>s;
char a[100];
int i,N;
scanf("%d\n",&N);
while(N--)
{
gets(a);
{
int k=1;
for(i=0;i<strlen(a);i++)
{
if(k==0) break;
if(a[i]==‘(‘||a[i]==‘[‘) s.push(a[i]);
if(a[i]==‘]‘||a[i]==‘)‘)
{
if(s.empty())
k=0;
else
{if(abs(s.top()-a[i])==1||abs(s.top()-a[i])==2) s.pop();
else k=0;
}
}
}
if(k==1&&s.empty()) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
while(!s.empty()) s.pop();
}
}
return 0;
}
#include<iostream>
using namespace std;
#include<stack>
#include<cstring>
#include<cmath>
int main()
{
stack<char>s;
char a[100];
int i;
while(gets(a))
{
int k=1;
for(i=0;i<strlen(a);i++)
{
if(k==0) break;
if(a[i]==‘(‘||a[i]==‘[‘) s.push(a[i]);
if(a[i]==‘]‘||a[i]==‘)‘)
{
if(s.empty())
k=0;
else
{if(abs(s.top()-a[i])==1||abs(s.top()-a[i])==2) s.pop();
else k=0;
}
}
}
if(k==1&&s.empty()) cout<<"yes"<<endl;
else cout<<"no"<<endl;
while(!s.empty()) s.pop();
}
return 0;
}