-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparenthesized.cpp
43 lines (34 loc) · 1.21 KB
/
parenthesized.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
#include <iostream>
#include <stack>
#include <string>
bool isWellParenthesized(const std::string& expression) {
std::stack<char> charStack;
for (char ch : expression) {
if (ch == '(' || ch == '{' || ch == '[') {
charStack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (charStack.empty()) {
return false; // Unbalanced closing parenthesis without an opening one
}
char top = charStack.top();
charStack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false; // Mismatched closing parenthesis
}
}
}
return charStack.empty(); // Check if there are any unmatched opening parenthesis left
}
int main() {
std::string expression;
std::cout << "Enter an expression: ";
std::getline(std::cin, expression);
if (isWellParenthesized(expression)) {
std::cout << "The expression is well-parenthesized.\n";
} else {
std::cout << "The expression is not well-parenthesized.\n";
}
return 0;
}