bool isValidParenthesis (string expression) {
stack<char> s;
for (int i = 0; i < expression.length(); i++) {
char ch = expression[i];
// if opening bracket push it to stack
// if closing bracket, pop from stack, check if the popped element is the matching opening bracket
if (ch == '(' || ch =='{' || ch == '[') {
s.push(ch);
}
else {
// for closing bracket
if (!s.empty()) {
char top = s.top();
if ((ch == ')' && top == '(') || (ch == '}' && top == '{') || (ch == ']' && top == '[')) {
s.pop();
}
}
else {
return false;
}
}
}
if (s.empty()) {
return true;
}
else {
return false;
}
}