class Solution {
public:
bool isValid(string s)
{
if(s.empty()||s.size()==1)
return false;
stack<char> stackdata;
int i=0;
const int n=s.size();
while(i<n)
{
while(s[i]=='(' || s[i]=='{' || s[i]=='[' && i<n)
{
stackdata.push(s[i]);
++i;
}
while(s[i]==')' || s[i]=='}' || s[i]==']' && i<n)
{
if(!stackdata.empty())
{
char temp=stackdata.top();
stackdata.pop();
if(temp=='('&& s[i]!=')' || temp=='['&& s[i]!=']'|| temp=='{'&& s[i]!='}')
return false;
if(temp=='('&& s[i]==')' || temp=='['&& s[i]==']'|| temp=='{'&& s[i]=='}')
++i;
}
else
return false;
}
}
if(!stackdata.empty())
return false;
else
return true;
}
};
Valid Parentheses
最新推荐文章于 2021-02-23 15:41:56 发布