题目描述
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
分析
这道题很容易想到使用栈。如果当前符号是左括号,就压入栈中;如果是右括号,就将栈顶元素弹出,判断是否匹配。最后遍历完字符串的字符后,判断一下栈是否为空即可。
AC代码如下:
class Solution {
public:
bool isValid(string s) {
if(s.empty())
{
return true;
}
stack<char> temp;
int length = s.length();
for(int i = 0; i < length; ++i)
{
if(s[i] == ')')
{
if(!temp.empty() && temp.top() == '(')
{
temp.pop();
continue;
}
else
{
return false;
}
}
if(s[i] == ']')
{
if(!temp.empty() && temp.top() == '[')
{
temp.pop();
continue;
}
else
{
return false;
}
}
if(s[i] == '}')
{
if(!temp.empty() && temp.top() == '{')
{
temp.pop();
continue;
}
else
{
return false;
}
}
temp.push(s[i]);
}
return temp.empty();
}
};