链接:https://leetcode.cn/problems/valid-parentheses/submissions/
法一:用栈辅助,判断括号是否闭合
注意点:isMatch函数中注意a和b谁为左括号、谁为右括号(栈顶元素应该是左括号,因为有效的括号必须先出现左括号)
#include<iostream>
#include<vector>
#include<stack>
#include<string>
using namespace std;
//{()}{
class Solution {
public:
bool isMatch(char a,char b){
return (b=='(' && a==')') || (b=='[' && a==']') || (b=='{' && a=='}');
}
bool isValid(string s) {
stack<char> x;
for(int i=0;i<s.size();i++){
if(x.empty()) x.push(s[i]);
else{
if(isMatch(s[i],x.top())) x.pop();
else x.push(s[i]);
}
}
return x.empty();
}
};
int main(){
//解锁cin,cout
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
Solution* obj=new Solution();
string s;
getline(cin,s);
cout<<obj->isValid(s)<<endl;
return 0;
}