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.
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
char c;
for (int i = 0; i < s.length(); ++i)
{
if (stk.empty() )
{
if (s[i] != '(' && s[i] != '{' && s[i] != '[') return false;
else stk.push(s[i]);
continue;
}
c = stk.top();
switch(s[i])
{
case ')':
if (c == '(') stk.pop();
else stk.push(s[i]);
break;
case '}':
if (c == '{') stk.pop();
else stk.push(s[i]);
break;
case ']' :
if (c == '[') stk.pop();
else stk.push(s[i]);
break;
default:
stk.push(s[i]);
break;
}
}
if (stk.empty())
return true;
else
return false;
}
};
int main()
{
Solution a;
cout << a.isValid("(])") << endl;
system("pause");
return 0;
}