-
Notifications
You must be signed in to change notification settings - Fork 15
/
valid_parenthesis_using stack.cpp
80 lines (70 loc) · 2 KB
/
valid_parenthesis_using stack.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*Given an expression string x.
Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{[()()]()}”
and 'false' for exp = “[(])”.*/
#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 s)
{
stack<char> st;
int i=0;
while(i<s.length()){
if(s[i]=='(' ||s[i]=='[' ||s[i]=='{')
st.push(s[i]);
else if(s[i]==')' ||s[i]=='}' ||s[i]==']'){
if(s[i]==')' ){
while(!st.empty() && st.top()!='('){
if(st.top()!='(')
return false;
st.pop();
}
if(st.empty())
return false;
st.pop();
}
if(s[i]=='}' ){
while(!st.empty() && st.top()!='{'){
if(st.top()!='{')
return false;
st.pop();
}
if(st.empty())
return false;
st.pop();
}
if(s[i]==']' ){
while(!st.empty() && st.top()!='['){
if(st.top()!='[')
return false;
st.pop();
}
if(st.empty())
return false;
st.pop();
}
}
i++;
// Your code here
}
if(st.empty())
return true;
return false;
}
};
// { Driver Code Starts.
int main()
{
int t;
string a;
cin>>a;
Solution obj;
if(obj.ispar(a))
cout<<"balanced"<<endl;
else
cout<<"not balanced"<<endl;
} // } Driver Code Ends