-
Notifications
You must be signed in to change notification settings - Fork 381
/
Check_Balance_parenthesis.cpp
67 lines (67 loc) · 1.7 KB
/
Check_Balance_parenthesis.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
#include<bits/stdc++.h>
using namespace std;
void balance_parentheses()
{
stack<char> st;
string str;
cout << "Enter string may or may not containing parentheses:: ";
cin >> str;
int flag = 0; //flag is an arbitrary variable
for (int i = 0; i < str.size();i++)
//for length of the string calculated by number of letters
{
if (str[i] == '{' || str[i] == '[' || str[i] == '(')
{
st.push(str[i]); //push function to enter terms in a stack;
flag = 1;
}
if (!st.empty())
{
if (str[i] == '}')
{
if (st.top() == '{') // top of the stack;
{
st.pop(); //pop function to delete terms from the top of array;
continue;
}
else
break;
}
if (str[i] == ']')
{
if (st.top() == '[')
{
st.pop();
continue;
}
else
break;
}
if (str[i] == ')')
{
if (st.top() == '(')
{
st.pop();
continue;
}
else
break;
}
}
else
break;
}
if ((st.empty()) && (flag == 1))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main()
{
int t;
cout << "Enter number of test cases:: ";
cin >> t;
for (int i = 0; i < t; i++)
balance_parentheses(); //calling of function for checking of brackets;
return 0;
}