您的位置:首页 > 其它

leetcode-20. Valid Parentheses

2016-04-27 21:30 441 查看
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.

思路:用stack,左括号进栈,右括号判断栈顶的是否是对应左括号,是的话出栈,否则false,循环最后栈为空则true

#include<string>
using namespace std;
class Solution {
stack<char> myStack;
public:
bool isValid(string s) {

for(int i=0;i<s.size();i++)
{
switch(s[i])
{
case '(':
case '[':
case '{':
myStack.push(s[i]);
break;

case ')':
if(myStack.empty() || myStack.top() != '(')
{
return false;
}
myStack.pop();
break;
case ']':
if(myStack.empty() || myStack.top() != '[')
{
return false;
}
myStack.pop();
break;
case '}':
if(myStack.empty() || myStack.top() != '{')
{
return false;
}
myStack.pop();
break;
}
}

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