基于栈:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> S;
for (int i = 0; i<s.size(); ++i)
{
switch (s[i])
{
case'(':S.push(s[i]); break;
case'{':S.push(s[i]); break;
case'[':S.push(s[i]); break;
case')':if (S.empty() || S.top() != '(')
return false;
else
S.pop(); break;
case ']':if (S.empty() || S.top() != '[')
return false;
else
S.pop(); break;
case '}':if (S.empty() || S.top() != '{')
return false;
else
S.pop(); break;
default:break;
}
}
return S.empty();
}
};
int main()
{
int N;
cin >> N;
string *a = new string[N]; //输入多组
for (int i = 0; i<N; i++)
{
a[i] = ""; //初始化
cin >> a[i];
}
Solution solution;
for (int i = 0; i<N; i++)
{
if (solution.isValid(a[i]) == true)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
system("pause");
return 0;
}
/*
bool isValid(string s) {
stack<char> S;
for(const auto& c : s){
switch(c){
case '{': S.push('}'); break;
case '[': S.push(']'); break;
case '(': S.push(')'); break;
default:
if(S.size() == 0 || c != S.top()) return false;
else S.pop();
}
}
return S.size() == 0;
}
*/
基于队列: