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> st;
for(int i=0;i<s.length();i++)
{
char c=s[i];
if(c=='(' || c=='[' || c=='{')
st.push(c);
else if(st.size()==0) return false;
else
{
char c2=st.top();
if((c2=='(' && c==')') || (c2=='[' && c==']') || (c2=='{' && c=='}'))
st.pop();
else return false;
}
}
if(st.size()>0) return false;
else return true;
}
};
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.length();i++)
{
char c=s[i];
if(c=='(' || c=='[' || c=='{')
st.push(c);
else if(st.size()==0) return false;
else
{
char c2=st.top();
if((c2=='(' && c==')') || (c2=='[' && c==']') || (c2=='{' && c=='}'))
st.pop();
else return false;
}
}
if(st.size()>0) return false;
else return true;
}
};

浙公网安备 33010602011771号