题目描述
给定一个表达式e,包含各种字符,如字母、数字、运算符、标点、空格和括号()[]{}等, 判断其中括号是否匹配,如是,则返回0, 否则根据错误类型返回1-3:
错误类型包括1、2、3类型:
类型1:
左右括号不匹配,如"(]", “(((]))))”, “((}”,“let {x=a[0)*(b+c); y=b}”
类型2:
发现有左括号不存在与之匹配的右括号,有多余的左括号,如"(“, “(([]”, “()(()”
类型3:
发现右括号不存在与之匹配的左括号,有多余的右括号,如")“, “())”,”(())”。
输入
第一行输入测试次数
第二行开始输入字符串
输出
如果成功匹配则输出yes
如果不成功则输出no,然后输出类型
输入样例
3
()
(]
(([]
输出样例
yes
no 1
no 2
代码
#include <iostream>
#include <stack>
#define MaxSize 100
using namespace std;
int BracketsCheck(string str, int length) {
stack<char> s;
for (int i = 0; i < length; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
s.push(str[i]);
else {
if (s.empty())
return 3;
char topElem;
if (str[i] == ')') {
topElem = s.top();
s.pop();
if (topElem != '(')
return 1;
}
if (str[i] == ']') {
topElem = s.top();
s.pop();
if (topElem != '[')
return 1;
}
if (str[i] == '}') {
topElem = s.top();
s.pop();
if (topElem != '{')
return 1;
}
}
}
if (!s.empty())
return 2;
return 0;
}
int main() {
int t;
cin >> t;
while (t--) {
string c;
cin >> c;
int aa = BracketsCheck(c, c.size());
if (aa)
cout << "no " << aa << endl;
else {
cout << "yes" << endl;
}
}
return 0;
}