Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include<bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- class Solution
- {
- public:
- //Function to check if brackets are balanced or not.
- bool ispar(string x)
- {
- // Your code here
- stack<int> s;
- for(int i=0;i<x.length();i++)
- {
- char ch=x[i];
- if(ch=='{' || ch=='(' || ch=='[')
- {
- s.push(ch);
- }
- else
- {
- if(s.empty())
- {
- return false;
- }
- else
- {
- char top=s.top();
- if(ch==']' && top=='[')
- {
- s.pop();
- }
- else if(ch==')' && top=='(')
- {
- s.pop();
- }
- else if(ch=='}' && top=='{')
- {
- s.pop();
- }
- else
- {
- return false;
- }
- }
- }
- }
- if(s.empty())
- {
- return true;
- }
- return false;
- }
- };
- //{ Driver Code Starts.
- int main()
- {
- int t;
- string a;
- cin>>t;
- while(t--)
- {
- cin>>a;
- Solution obj;
- if(obj.ispar(a))
- cout<<"balanced"<<endl;
- else
- cout<<"not balanced"<<endl;
- }
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment