Description
检查输入字符串中的括号是否匹配。括号包括:{, }, (, ), [, ].
Input
第一行是一整数,即测试样例个数n.
以下n行,每一行是一个长度不超过100个字符的字符串。
Output
第一行是一整数,即测试样例个数n.
以下n行,每一行是一个长度不超过100的字符串。
Sample Input
3
a
2-[(1+2)*2]
(a+b])
Sample Output
Yes
Yes
No
参考答案
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int testnum=0;
cin>>testnum;
for(int j=0;j<testnum;++j){
char s[100],a[100];
int top=0;
cin>>s;
int length=strlen(s);
for(int i=0;i<length;i++){
if((s[i]=='('||s[i]=='[')||s[i]=='{'){
++top;
a[top]=s[i];
}
else if(s[i]==')'){
if(a[top]=='('){
top--;
}
else{
top=100;
break;
}
}
else if(s[i]==']'){
if(a[top]=='['){
top--;
}
else{
top=100;
break;
}
}
else if(s[i]=='}'){
if(a[top]=='{'){
top--;
}
else{
top=100;
break;
}
}
}
if(top>0){
cout<<"No"<<endl;
}
else{
cout<<"Yes"<<endl;
}
top=0;
}
}
ZHC的答案
//括号判断
#include<iostream>
using namespace std ;
class Stack{
private:
char s[100] ;
int num;
bool match ;
public:
Stack(){
num = 0 ;
match = true ;
}
void pop(const char t){
if(t=='(' || t=='[' || t=='{'){
s[num] = t;
num++;
}
else if(t==')' || t==']' || t=='}'){
if(num==0) match = false ;
if(num>0){
if( t==')' && s[num-1]=='(' ){
--num; }
else if( t==']' && s[num-1]=='[' ){
--num; }
else if( t=='}' && s[num-1]=='{' ){
--num; }
else match = false ;
}
}
}
void judge(const string s){
for(int i = 0 ; i<s.size() ; ++i ){
this->pop( s.at(i) );
}
}
bool getmatch()const{
if(num==0) return this->match;
else return false ; }
void Match()const{
if( this->getmatch() ) cout<<"Yes" ;
else cout<<"No" ;
}
};
int main()
{
Stack strs ;
string s ;
cin>>s ;
strs.judge(s) ;
strs.Match() ;
return 0;
}
//括号判断
#include
using namespace std ;
class Stack{
private:
char s[100] ;
int num;
bool match ;
public:
Stack(){
num = 0 ;
match = true ;
}
void pop(const char t){
if(t=='(' || t=='[' || t=='{'){
s[num] = t;
num++;
}
else if(t==')' || t==']' || t=='}'){
if(num==0) match = false ;
if(num>0){
if( t==')' && s[num-1]=='(' ){
--num; }
else if( t==']' && s[num-1]=='[' ){
--num; }
else if( t=='}' && s[num-1]=='{' ){
--num; }
else match = false ;
}
}
}
void judge(const string s){
for(int i = 0 ; ipop( s.at(i) );
}
}
bool getmatch()const{
if(num==0) return this->match;
else return false ; }
void Match()const{
if( this->getmatch() ) cout