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> stk;
for (int i = 0; i < s.size(); i++){
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
stk.push(s[i]);
if (s[i] == ')'||s[i]==']'||s[i]=='}'){
if(stk.empty())
return false;
if ((s[i] == ')'&&stk.top() == '(') ||
(s[i] == ']'&&stk.top() == '[') ||
(s[i] == '}'&&stk.top() == '{'))
stk.pop();
else
return false;
}
}
if (stk.empty())
return true;
else
return false;
}
};