题目:
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> st;
for(int i = 0; i < s.size(); i++)
if (s[i] == ')' || s[i] == ']' || s[i] == '}')
{
if (st.empty())
return false;
else
{
char c = st.top();
st.pop();
if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}'))
return false;
}
}
else
st.push(s[i]);
return st.empty();
}
};