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.
A: 用栈模拟
bool isOpenBracket(char c)
{
if(c=='('||c=='['||c=='{')
return true;
else return false;
}
class Solution {
public:
bool isValid(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// use stack
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(isOpenBracket(s[i]))
st.push(s[i]);
else
{
if(st.empty())
return false;
char c = st.top();
st.pop();
if((s[i]==')'&&c=='(')||(s[i]==']'&&c=='[')||(s[i]=='}'&&c=='{'))
continue;
else
return false;
}
}
return st.empty();
}
};