您的位置:首页 > 其它

leetcode题解:Valid Parentheses(栈的应用-括号匹配)

2014-07-07 16:21 375 查看
题目:

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)括号可嵌套,如{[()]}

实现:

class Solution {
public:
bool isValid(string s) {
if(s.empty()) return false;//空字符串,false
int len=strlen(s.c_str());
if(len==1) return false;//只有一个字符,false
char pre;
stack<char> char_stack;
for(int i=0;i<len;i++)
{
if(isPop(s[i])) //该出栈顶元素
{
if(!char_stack.empty())
{
pre=char_stack.top();//取栈顶元素、并出栈
char_stack.pop();
if(!isChar(pre,s[i]))//是否匹配
return false;
}
else return false;
}
else //入栈
{
char_stack.push(s[i]);
}
}
return char_stack.empty();//栈空true,否则false
}
private:
bool isPop(char t) //判断是否是)} ]符号,是则出栈栈顶元素
{
if(t==')'||t=='}'||t==']')
return true;
else
return false;
}
bool isChar(char t1,char t2)//判断两字符t1,t2是否匹配
{
switch (t1)
{
case '(':
{
if(t2==')') return true;
else return false;
break;
}
case '{':
{
if(t2=='}') return true;
else return false;
break;
}
case '[':
{
if(t2==']') return true;
else return false;
break;
}
default:
return false;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: