-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathbalanced parenthesis.c++
More file actions
62 lines (61 loc) · 886 Bytes
/
balanced parenthesis.c++
File metadata and controls
62 lines (61 loc) · 886 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool check(char x, char y)
{
if ((x=='(' && y==')') || (x=='{' && y=='}') || (x=='[' && y==']') || (x=='<' && y=='>'))
{
return true;
}
else
{
return false;
}
}
bool checkbalancedparenthesis(string s)
{
stack<char> st;
int top=-1;
int l=s.length();
for(int i=0;i<l;i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
{
st.push(s[i]);
top=top+1;
}
else if(s[i]==')' || s[i]=='}' || s[i]==']')
{
if(top==-1 || check(st.top(),s[i])==false)
{
return false;
}
else
{
st.pop();
top=top-1;
}
}
}
if(top==-1)
return true;
else
return false;
}
int main()
{
// your code goes here
int test;
cin>>test;
while(test-->0)
{
string s;
cin>>s;
if(checkbalancedparenthesis(s)==true)
cout<<"BALANCED"<<endl;
else
cout<<"NOT BALANCED"<<endl;
}
return 0;
}