试题名称 括号配对问题
时间限制: 1 秒
内存限制: 10KB
问题描述
现在有一行括号序列,请你检查这行括号是否配对。
输入说明
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符。
输出说明
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No。
输出样例
No
No
Yes
== 这题目就不写注释了,应该都能看懂==
#include<iostream>
#include<stack>
#include<string>
using namespace std;
void match(string s);
int main() {
int n;
cin >> n;
string s;
for (int i = 0; i < n; i++) {
cin >> s;
match(s);
}
return 0;
}
void match(string s) {
stack<char> sta;
for (int i = 0; i < s.length(); i++) {
if (sta.empty())
sta.push(s[i]);
else {
if (s[i] == '[' || s[i] == '(')
sta.push(s[i]);
else {
if (s[i] == ']') {
if (sta.top() == '[') {
sta.pop();
}
else {
sta.push(s[i]);
}
}
else if (s[i] == ')') {
if (sta.top() == '(') {
sta.pop();
}
else {
sta.push(s[i]);
}
}
}
}
}
if (sta.empty())
cout << "Yes" << endl;
else
cout << "No" << endl;
}
ps:如有错误敬请指正,如有问题欢迎评论区讨论或私信。如果未及时回复请微信私聊我。
微信号: z1654407501
如果对你有用的话,请点赞并关注支持一波.