假设表达式中允许包含两种括号:圆括号和方括号其嵌套的顺序随意但需要成对出现。即或 等为正确的格式 或 或 均为不正确的格式。给定一串括号输入换行作为结束符检测格式是否正确若正确输出YES;错误输出NO。输入第一行一个正整数T表示有T组测试数据接下来T行每行一个字符串。输出T行每一行一个YES 或 NO。样例输入 复制2样例输出 复制YESNOC++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool checkParentheses(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[') {
st.push(c);
} else if (c == ')' || c == ']') {
if (st.empty()) {
return false;
}
char top = st.top();
st.pop();
if ((c == ')' && top != '(') || (c == ']' && top != '[')) {
return false;
}
}
}
return st.empty();
}
int main() {
int T;
cin >> T;
cin.ignore();
for (int i = 0; i < T; i++) {
string s;
getline(cin, s);
if (checkParentheses(s)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
原文地址: http://www.cveoy.top/t/topic/ja36 著作权归作者所有。请勿转载和采集!