7-4 括号匹配 (15 分)
给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。
输入格式:
第一行一个整数T(T<=10)
其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)
输出格式:
对于每个字符串,匹配输出Yes,否则输出No
输入样例:
2 {()[]} ([)]
输出样例:
Yes No
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
stack<char> s;
int main(){
int t;
cin >> t;
getchar();
while (t--) {
char ch;
int count = 0;
while (s.size()) s.pop();
while (ch = getchar(), ch != '\n') {
if (ch == '(' || ch == '[' || ch == '{') {//压入左括号
s.push(ch);
continue;
}
if (s.empty()) {//如果在栈空的时候输入了任意右括号,判定为No
count = 1;
continue;
}
//配对
else if (s.top() == '(') {
if (ch == ')') s.pop();
else count = 1;
}
else if (s.top() == '[') {
if (ch == ']') s.pop();
else count = 1;
}
else if (s.top() == '{') {
if (ch == '}') s.pop();
else count = 1;
}
}
if (count == 0&&s.empty()) {
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
return 0;
}