题目:判断各种括号是否正确匹配
分析:用栈来解决,左边的括号push进去,右边的括号则判断是否在栈顶有对应的左括号。
还有一种方法是搜索字符串,有效的字符串里必定有一组括号是相邻且匹配的。
答案:
class Solution {
public:
bool isValid(string s) {
int len = s.length();
stack<char> stk;
bool result = true;
for (int i = 0; i < len; i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
stk.push(s[i]);
else
{
if (s[i] == ')')
{
if (!stk.empty() && stk.top() == '(')
stk.pop();
else
{
result = false;
break;
}
}
if (s[i] == ']')
{
if (!stk.empty() && stk.top() == '[')
stk.pop();
else
{
result = false;
break;
}
}
if (s[i] == '}')
{
if (!stk.empty() && stk.top() == '{')
stk.pop();
else
{
result = false;
break;
}
}
}
}
if (!stk.empty())
result = false;
return result;
}
};