Skip to main content

Parenthesis Checker

Task: Find the given Parenthesis string is balanced on not.

Example:
Input:
1
{[()]}
Output:
balanced

Here is the Code:
Program in C++:

  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. string parenthesChecker(string s)
  5. {
  6.     stack<char> st;
  7.     if(s[0]==')'||s[0]==']'||s[0]=='}')
  8.     {
  9.         return "not balanced";
  10.     }
  11.     for(int i=0;i<s.length();i++)
  12.     {
  13.         if(s[i]=='('||s[i]=='['||s[i]=='{')
  14.         {
  15.             st.push(s[i]);
  16.         }
  17.         else
  18.         {
  19.             if(st.empty()==false)
  20.             {
  21.                if((s[i]==')'&&st.top()=='(')||(s[i]==']'&&st.top()=='[')||(s[i]=='}'&&st.top()=='{'))
  22.                 {
  23.                     st.pop();
  24.                 }
  25.                 else
  26.                 {
  27.                     break;
  28.                 }
  29.             }
  30.         }
  31.     }
  32.     if(st.empty()) 
  33.     {
  34.         return "balanced";
  35.     }
  36.     else 
  37.     {
  38.         return "not balanced";
  39.     }
  40. }
  41. int main()
  42.  {
  43. int t;
  44. cin>>t;
  45. while(t--)
  46. {
  47.     string s;
  48.     cin>>s;
  49.     cout<<parenthesChecker(s)<<endl;
  50. }
  51. return 0;
  52. }

Here is the Video: