Example 1:
Input: "()[]{}"
Output: true
Example 2:
Input: "(]"
Output: false
Example 3:
Input: "([)]"
Output: false
class Solution
{
public:
bool isValid(string s)
{
if (s.length() == 0)
{
return true;
}
int x = 0;
stack<int> k;
bool res = true;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
{
k.push(s[i]);
}
else if(!k.empty())
{
if (s[i] == ')' && k.top() == '(')
{
k.pop();
}
else if (s[i] == '}' && k.top() == '{')
{
k.pop();
}
else if (s[i] == ']' && k.top() == '[')
{
k.pop();
}
else
{
x = 1;
res = false;
break;
}
}
else{
x = 1;
res = false;
break;
}
}
if (x == 0 && !k.empty())
{
res = false;
}
return res;
}
}