Valid Parenthesis String in C++

C++Server Side ProgrammingProgramming

Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid.

To solve this, we will follow these steps −

  • Traverse through the expression until it has exhausted
    • if the current character is opening bracket like (, { or [, then push into stack
    • if the current character is closing bracket like ), } or ], then pop from stack, and
    • check whether the popped bracket is corresponding starting bracket of the
    • current character, then it is fine, otherwise, that is not balanced.
  • After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced.


Let us see the following implementation to get better understanding −

 Live Demo

#include <iostream>
#include <stack>
using namespace std;
bool isBalancedExp(string exp) {
   stack<char> stk;
   char x;
   for (int i=0; i<exp.length(); i++) {
      if (exp[i]=='('||exp[i]=='['||exp[i]=='{') {
      if (stk.empty())
         return false;
      switch (exp[i]) {
      case ')':
         x =;
         if (x=='{' || x=='[')
            return false;
      case '}':
         x =;
         if (x=='(' || x=='[')
            return false;
      case ']':
         x =;
         if (x =='(' || x == '{')
            return false;
   return (stk.empty());
int main() {
   string expresion = "()[(){()}]";
   if (isBalancedExp(expresion))
      cout << "This is Balanced Expression";
      cout << "This is Not Balanced Expression";




This is Balanced Expression
Published on 31-Jan-2020 11:22:24