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.
V1
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i = 0; i < s.size(); ++i)
{
char ch = s.at(i);
if(st.empty())
st.push(ch);
else
{
if('(' == ch || '[' == ch || '{' == ch)
st.push(ch);
else if(')' == ch && '(' == st.top())
st.pop();
else if(']' == ch && '[' == st.top())
st.pop();
else if('}' == ch && '{' == st.top())
st.pop();
}
}
return st.empty();
}
};
V2
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i = 0; i < s.size(); ++i)
{
char ch = s.at(i);
if(st.empty())
st.push(ch);
else
{
//ascii number:
//'(' = 40; ')' = 41
//'[' = 91; ']' = 93
//'{' = 123; '}' = 125
if(1 == ch - st.top() || 2 == ch - st.top())
st.pop();
else
st.push(ch);
}
}
return st.empty();
}
};