-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
104 lines (89 loc) · 2.26 KB
/
Copy pathmain.cpp
File metadata and controls
104 lines (89 loc) · 2.26 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isBalanced(const string& expression, int& errorPosition)
{
stack<pair<char, int>> st;
for (int i = 0; i < expression.length(); i++)
{
char ch = expression[i];
// Opening bracket
if (ch == '(' || ch == '[' || ch == '{')
{
st.push({ch, i});
}
// Closing bracket
else if (ch == ')' || ch == ']' || ch == '}')
{
// Closing bracket found but no opening bracket exists
if (st.empty())
{
errorPosition = i;
return false;
}
char top = st.top().first;
// Check matching pair
if ((ch == ')' && top == '(') ||
(ch == ']' && top == '[') ||
(ch == '}' && top == '{'))
{
st.pop();
}
else
{
errorPosition = i;
return false;
}
}
}
// Some opening bracket was never closed
if (!st.empty())
{
errorPosition = st.top().second;
return false;
}
return true;
}
int main()
{
string expression;
int errorPosition = -1;
bool hasBracket = false;
cout << "================================\n";
cout << " BALANCED PARENTHESES CHECKER\n";
cout << "================================\n";
cout << "\nEnter an expression: ";
getline(cin, expression);
// Empty input
if (expression.empty())
{
cout << "\nInvalid input! Expression cannot be empty.\n";
return 0;
}
// Check whether input contains at least one bracket
for (char ch : expression)
{
if (ch == '(' || ch == ')' ||
ch == '[' || ch == ']' ||
ch == '{' || ch == '}')
{
hasBracket = true;
break;
}
}
if (!hasBracket)
{
cout << "\nInvalid input! No brackets found.\n";
}
else if (isBalanced(expression, errorPosition))
{
cout << "\nExpression is BALANCED\n";
}
else
{
cout << "\nExpression is NOT BALANCED\n";
cout << "Error at position: " << errorPosition << "\n";
}
return 0;
}