Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
思路:利用栈,当遇到第一个后扩号时,如果此时前一个符号不与之配对,那么肯定是错误的。如果与之配对,那么把配对的这一组一起出栈。
class Solution {
public:
bool isValid(string str) {
stack<char> s1;
int num ;
num = str.size();
if(num % 2)
return false;
int i = 0;
s1.push('0');
while(str[i] != '\0')
{
s1.push(str[i]);
if(s1.top()=='}')
{
s1.pop();
if(s1.top()!='{')
{
return false;
}
else
{
s1.pop();
}
}
else if(s1.top()==')')
{
s1.pop();
if(s1.top()!='(')
{
return false;
}
else
{
s1.pop();
}
}
else if(s1.top() == ']')
{
s1.pop();
if(s1.top()!='[')
{
return false;
}
else
{
s1.pop();
}
}
i++;
}
if(s1.top() == '0')
return true;
else
return false;
}
};