您的位置:首页 > 其它

Valid Parentheses

2016-03-14 21:16 302 查看
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.

通过一个栈即可解决问题,但是对于一些特殊的输入需要特别考虑,比如说单个括号作为输入,“(”可以通过判断栈是否为空来进行判定,“)”则可以说没有匹配项来判定。

class Solution {
public:
bool isValid(string s) {
stack<char>stack;
for (int i = 0; i < s.size(); ++i){
if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
stack.push(s[i]);
continue;
}
if (!stack.empty()){
char c = stack.top();
switch (s[i]){
case ')':
{
if (c == '(')
{
stack.pop();
break;
}
else
return false;
}
case ']':
{
if (c == '[')
{
stack.pop();
break;
}
else
return false;
}

case '}':
{
if (c == '{')
{
stack.pop();
break;
}
else
return false;
}
default:
break;
}
}
else
return false;
}
if (!stack.empty())
return false;
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: