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)stack<char>的数据结构,stk.push(elem),stk.pop(),stk.top等用法。
2)栈为空,输入为左括弧,输入为右括弧,分不同情况讨论,入栈,出栈,退出,continue等
class Solution {
public:
bool correct_pair(char elem,char elem2)
{
if(((elem == ‘(‘)&&(elem2 == ‘)‘))||((elem == ‘[‘)&&(elem2 == ‘]‘))||((elem == ‘{‘)&&(elem2 == ‘}‘)))
return true;
else
return false;
}
bool isbegin(char s)
{
if((s == ‘(‘)||(s == ‘{‘)||(s == ‘[‘))
return true;
else
return false;
}
bool is_end(char s)
{
if((s == ‘)‘)||(s == ‘}‘)||(s == ‘]‘))
return true;
else
return false;
}
bool isValid(string s) {
int n = s.size();
stack<char> stk;
if(0 == n)
{
return true;
}
for(int i = 0;i < n;i++)
{
if(0 == stk.size())
{
stk.push(s[i]);
continue;
}
if(isbegin(s[i]))
{
stk.push(s[i]);
}
else if(is_end(s[i]))
{
if(correct_pair(stk.top(),s[i]))
{
stk.pop();
continue;
//s.push(s[i]);
}
else
return false;
}
}
if(0 == stk.size())
return true;
else
return false;
}
};