pintia7-1 括号匹配 (25 分)
给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入格式:
输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。
输出格式:
如果括号配对,输出yes,否则输出no。
输入样例1:
sin(10+20)
输出样例1:
yes
输入样例2:
{[}]
输出样例2:
no
#include <bits/stdc++.h>
using namespace std;
struct SqStack{
char *base;
char *top;
int stacksize;
};
void InitStack(SqStack &S) {
S.base = new char[1000];
S.top = S.base;
S.stacksize = 1000;
}
int Push(SqStack &S, char e) {
if (S.top - S.base == S.stacksize) return 0;
*S.top++ = e;
return 1;
}
char Pop(SqStack &S) {
if (S.top == S.base)return 0;
char b;
b = *--S.top;
return b;
}
int main()
{
SqStack S;
InitStack(S);
string a;
getline(cin, a);
int i;
bool flag =1;
for (i = 0; i < a.length() && i < 100; i++) {
if (a[i] == '(') {
Push(S, ')');
}
else if (a[i] == '[') {
Push(S, ']');
}
else if (a[i] == '{') {
Push(S, '}');
}
else if (a[i] == ')' || a[i] == ']' || a[i] == '}')
{
if (Pop(S)==a[i] ) {}
else {
flag = 0;break; //错误即退出
}
}
}
if(S.top!=S.base)flag=0; //避免前后括号 数量不匹配
if (flag) {
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
}