Valid Parentheses
Q: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: 堆栈的应用。遇到opensymbol,则入栈;遇到close symbol,从栈中pop一个open symbol比较(栈为空,invalid),不匹配,invalid;遍历结束后,如果栈不为空,invalid;!!!
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s.size()%2!=0)
return false;
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i]=='{'||s[i]=='['||s[i]=='(')
st.push(s[i]);
else
{
if(st.empty())
return false;
char openSymbol = st.top();
st.pop();
if((s[i]==']'&&openSymbol=='[')||(s[i]=='}'&&openSymbol=='{')||(s[i]==')'&&openSymbol=='('))
continue;
else
return false;
}
}
return (st.empty()?true:false); //ATT!
}
浙公网安备 33010602011771号