-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced_parenthesis.cpp
75 lines (69 loc) · 1.6 KB
/
balanced_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
68
69
70
71
72
73
74
75
/*Nikhil*/
/*
Balanced Brackets/parenthesis in an expression
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;
bool ispar(string x)
{
stack<char> st;
int n = x.size();
for (int i = 0; i < n; i++)
{
if (st.empty())
{
st.push(x[i]);
}
else
{
if (x[i] == ')')
{
if (st.top() == '(')
{
st.pop();
}
else
{
st.push(x[i]);
}
}
else if (x[i] == ']')
{
if (st.top() == '[')
{
st.pop();
}
else
{
st.push(x[i]);
}
}
else if (x[i] == '}')
{
if (st.top() == '{')
{
st.pop();
}
else
{
st.push(x[i]);
}
}
else
{
st.push(x[i]);
}
}
}
return st.empty();
}
int main()
{
string a = "{([])}";
string b = "{([]))";
cout << "String a is Valid: " << ispar(a) << endl;
cout << "String b is Valid: " << ispar(b) << endl;
return 0;
}