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;
}
};