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.
此题难度不大,是基本的思路。右边字符是要匹配消掉的。左边是存入的!所以重点在右边字符!
bool isValid(string s) {
int i = 0;
int index = 0;
string right_str = ")}]";
string left_str = "({[";
stack<char> my_stack;
while(s[i] != '\0')
{
if((index=right_str.find(s[i])) >= 0)
{
if(my_stack.empty())
{
return false;
}
else
{
//另一种非索引方式
//if((my_stack.top() == '('&&s[i]==')')||(my_stack.top() == '{'&&s[i]=='}')||(my_stack.top() == '['&&s[i]==']'))
if(my_stack.top() == left_str[index])
my_stack.pop();
else
return false;
}
}
else
{
my_stack.push(s[i]);
}
i++;
}
return my_stack.empty();
}