# 括号匹配算法

### 输入样例:

``````2
{()[]}
([)]
``````

### 输出样例:

``````Yes
No
``````

### 题解

``````/*
1.建立栈,左括号压入,同时压入对应的右括号
2.遇到右括号弹出,看是否与栈顶元素匹配

*/
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

int main() {
vector<bool> ans;
int n;
cin >> n;
string str;
while (n-- > 0) {
cin>>str;
stack<char> sta;
int length=str.size();
if(length==0){
ans.push_back(true);
continue;
}
if(length%2){
ans.push_back(false);
continue;
}
sta.push(str[0]);
for(int i=1;i<length;i++){
if(sta.empty()){
sta.push(str[i]);
}
if(str[i]-sta.top()==1||str[i]-sta.top()==2){//利用asc2码
sta.pop();
}else{
sta.push(str[i]);
}
}
if(sta.empty()){
ans.push_back(true);
}else{
ans.push_back(false);
}
}
//控制输出，pta要求输出比较麻烦
bool flag = true;
for(bool out:ans){
if(flag==true){
if(out==1){
cout<<"Yes";
}else{
cout<<"No";
}
flag=false;
}else{
if(out==1){
cout<<endl<<"Yes";
}else{
cout<<endl<<"No";
}
}
}
system("pause");
}``````

``````    cin>>str;
stack<char> sta;
int length=str.size();
if(length==0){
ans.push_back(true);
continue;
}
if(length%2){
ans.push_back(false);
continue;
}
sta.push(str[0]);
for(int i=1;i<length;i++){
if(sta.empty()){
sta.push(str[i]);
}
if(str[i]-sta.top()==1||str[i]-sta.top()==2){//利用asc2码
sta.pop();
}else{
sta.push(str[i]);
}
}
if(sta.empty()){
ans.push_back(true);
}else{
ans.push_back(false);
}``````

``````bool isValid(string str) {
stack<char> sta;
if (str.length() % 2) {
return false;
}
for (int i = 0; i < str.size(); i++) {
if (sta.empty()) {
sta.push(str[i]);
} else if (str[i] - sta.top() == 1 || str[i] - sta.top() == 2) {
sta.pop();
}else{
sta.push(str[i]);
}

}
return sta.empty();
}``````