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> ss;
int len = s.size();
for(int i = 0; i < len; ++ i)
{
if(ss.empty())
ss.push(s[i]);
else
{
if(s[i] == ')')
{
if(ss.top() != '(') return false;
else ss.pop();
}
else if(s[i] == '}')
{
if(ss.top() != '{') return false;
else ss.pop();
}
else if(s[i] == ']')
{
if(ss.top() != '[') return false;
else ss.pop();
}
else
ss.push(s[i]);
}
}
if(!ss.empty()) return false;
return true;
}
};