nyist 2 括弧配對問題

來源:互聯網
上載者:User

標籤: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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.