Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
利用vector的push_back()与pop_back()来模仿栈操作
class Solution {
public:
bool isValid(string s) {
vector<char> str;
for(int i = 0; i < s.length();i++)
{
if(s.at(i) =='('|| s.at(i) == '{' || s.at(i) == '[')
{
str.push_back(s.at(i));
}
if(s.at(i) == ')' ||s.at(i) == '}' || s.at(i) == ']')
{
if(str.empty())
{
return false;
}
char c = str.back();
if(s.at(i) == ')' && c =='(')
{
str.pop_back();
}
else if(s.at(i) == '}' && c =='{')
{
str.pop_back();
}
else if(s.at(i) == ']' && c =='[')
{
str.pop_back();
}
else
{
return false;
}
}
}
if(str.empty())
{
return true;
}
else
{
return false;
}
}
};