-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ3.cpp
More file actions
46 lines (39 loc) · 1.13 KB
/
Copy pathQ3.cpp
File metadata and controls
46 lines (39 loc) · 1.13 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
#include <iostream>
#include <stack>
using namespace std;
bool isBalanced(string exp) {
stack<char> s;
for (int i = 0; i < exp.length(); i++) {
char ch = exp[i];
// if opening bracket, push it
if (ch == '(' || ch == '{' || ch == '[') {
s.push(ch);
}
// if closing bracket, check top of stack
else if (ch == ')' || ch == '}' || ch == ']') {
if (s.empty()) {
return false; // nothing to match
}
char top = s.top();
s.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false; // mismatch
}
}
}
// stack should be empty if balanced
return s.empty();
}
int main() {
string exp;
cout << "Enter an expression: ";
cin >> exp;
if (isBalanced(exp)) {
cout << "Expression has Balanced Parentheses" << endl;
} else {
cout << "Expression does NOT have Balanced Parentheses" << endl;
}
return 0;
}