地址:https://leetcode-cn.com/problems/valid-parentheses/
思路:利用栈stack处理,对于s[i],判断其是否与栈首匹配,若匹配则将栈首出栈,否则将s[i]入栈,最后判断栈是否为空即可
Code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<unordered_map>
using namespace std;
class Solution{
public:
bool isValid(string s){
stack<char> sta;
map<char,int> ma={{'(',-1}, {')',1}, {'{',-2}, {'}',2}, {'[',-3}, {']',3}};
for(int i=0;i<s.size();++i)
{
if(!sta.empty()&&ma[s[i]]>0&&ma[sta.top()]+ma[s[i]]==0){
sta.pop();
}else sta.push(s[i]);
}
return sta.empty();
}
};
int main()
{
string str;
Solution So;
cin>>str;
cout<<So.isValid(str)<<endl;
return 0;
}