-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_Parentheses_Balancing.cpp
More file actions
63 lines (52 loc) · 1.4 KB
/
02_Parentheses_Balancing.cpp
File metadata and controls
63 lines (52 loc) · 1.4 KB
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
//***********************************************************************//
// Description: Check for balanced parentheses in an expression. //
// Checks for balanced (), {}, and []. //
// //
// GitHub: https://github.com/ajbasu //
//***********************************************************************//
#include<iostream>
#include<string>
#include<stack>
using namespace std;
bool IsAPair(char,char);
bool IsAParentheses(char);
int main()
{
string str;
int str_size=0;
stack<char> s;
cout<<"Enter the string: ";
getline (cin,str);
str_size = str.size();
for(int i=0; i<str_size; i++)
{
char current = str[i];
if(!IsAParentheses(current)) continue;
if(s.size() > 0)
if(IsAPair(current,s.top()))
s.pop();
else
s.push(current);
else
s.push(current);
}
if(s.size() == 0)
cout<<"Balanced"<<endl;
else
cout<<"Not balanced"<<endl;
return 0;
}
bool IsAPair(char a, char b)
{
bool result = false;
if( (a == ')' && b == '(') || (a == '}' && b == '{') || (a == ']' && b == '[') )
result = true;
return result;
}
bool IsAParentheses(char a)
{
bool result = false;
if( a == ')' || a == '(' || a == '}' || a == '{' || a == ']' || a == '[' )
result = true;
return result;
}