jayati

Parenthesis Checker

Oct 5th, 2023
1,327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7.  
  8. class Solution
  9. {
  10.     public:
  11.     //Function to check if brackets are balanced or not.
  12.     bool ispar(string x)
  13.     {
  14.         // Your code here
  15.         stack<int> s;
  16.         for(int i=0;i<x.length();i++)
  17.         {
  18.             char ch=x[i];
  19.             if(ch=='{' || ch=='(' || ch=='[')
  20.             {
  21.                 s.push(ch);
  22.             }
  23.             else
  24.             {
  25.                 if(s.empty())
  26.                 {
  27.                     return false;
  28.                 }
  29.                 else
  30.                 {
  31.                     char top=s.top();
  32.                     if(ch==']' && top=='[')
  33.                     {
  34.                         s.pop();
  35.                     }
  36.                     else if(ch==')' && top=='(')
  37.                     {
  38.                         s.pop();
  39.                     }
  40.                     else if(ch=='}' && top=='{')
  41.                     {
  42.                         s.pop();
  43.                     }
  44.                     else
  45.                     {
  46.                         return false;
  47.                     }
  48.                 }
  49.             }
  50.         }
  51.         if(s.empty())
  52.         {
  53.             return true;
  54.         }
  55.         return false;
  56.     }
  57.  
  58. };
  59.  
  60. //{ Driver Code Starts.
  61.  
  62. int main()
  63. {
  64.    int t;
  65.    string a;
  66.    cin>>t;
  67.    while(t--)
  68.    {
  69.        cin>>a;
  70.        Solution obj;
  71.        if(obj.ispar(a))
  72.         cout<<"balanced"<<endl;
  73.        else
  74.         cout<<"not balanced"<<endl;
  75.    }
  76. }
  77. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment