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.
第一次遇到栈的题目,栈的用法转载了别人的文章。
1、pop()仅仅是移除第一个元素,top()才会返回元素。
2、不仅仅是这道题,任何题要事先考虑好所有可能的输入情况。
class Solution {
public:
bool isValid(string s) {
int i;
if(s.size()%2!=0)
return false;
stack<char> st;
for(i=0;i<s.size();i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')
st.push(s[i]);
else if(s[i]==')')
{
if(st.empty()||st.top()!='(')
return false;
else
st.pop();
}
else if(s[i]==']')
{
if(st.empty()||st.top()!='[')
return false;
else
st.pop();
}
else if(s[i]=='}')
{
if(st.empty()||st.top()!='{')
return false;
else
st.pop();
}
}
if(st.empty())
return true;
else
return false;
}
};