您的位置:首页 > 其它

LeetCode | 20. Valid Parentheses

2017-04-24 20:36 555 查看
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.

其实是括号匹配问题,用栈来实现比较方便.

//3ms AC
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if(len%2 == 1)
return false;
stack<char> symbol;
for(int i=0;i<len;i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
{
symbol.push(s[i]);
}
else                        //右括号
{
if(symbol.empty())      //栈为空,肯定不匹配
{
return false;
}
switch(s[i])
{
case ')':{
if(symbol.top() != '(')
return false;
break;
}
case ']':{
if(symbol.top() != '[')
return false;
break;
}
case '}':{
if(symbol.top() != '{')
return false;
break;
}
default:
break;
}
symbol.pop();
}
}
if(symbol.empty())
return true;
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode