题目要求:https://leetcode.com/problems/valid-parentheses/
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.
即求括号是否有效匹配!
解题思路:遇到左括号入栈,遇到右括号出栈!要考虑一些特殊情况。比如遇到右括号的时候出栈要检查栈此时是否为空!
源代码如下
class Solution {
public:
bool isValid(string s) {
stack<char> str;
for(int i = 0 ; i < s.size();i++)
{
if(s[i] == '(' || s[i] == '{' || s[i] == '[')
str.push(s[i]);
else if(s[i] == ')' )
{
if(!str.empty() && str.top() == '(')//要判断是否为空
str.pop();
else
return false;
}
else if(s[i] == ']')
{
if(!str.empty() && str.top() == '[')
str.pop();
else
return false;
}
else if(s[i] == '}')
{
if(!str.empty() && str.top() == '{')
str.pop();
else
return false;
}
}
return str.empty();
}
};