题目如下:
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.
分析:
先出现的括号,后比较,因此这就是一个栈的数据结构。
代码如下:
bool isValid(string s)
{
int length=s.size();
// if(length%2==1) return false;
stack<char> Parentheses;
for(int i=0;i<length;i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
if(s[i]=='(')
Parentheses.push(')');
if(s[i]=='[')
Parentheses.push(']');
if(s[i]=='{')
Parentheses.push('}');
}
else
{
if(Parentheses.size()==0)
return false;
if(Parentheses.top()!=s[i])
{
return false;
}
Parentheses.pop();
}
}
if(Parentheses.size()==0)
return true;
else
return false;
}