-
Notifications
You must be signed in to change notification settings - Fork 246
/
9.52.cpp
67 lines (60 loc) · 2.07 KB
/
9.52.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 <stack>
#include <string>
#include <iostream>
// Currently, this program will only examine whether all parentheses are
// matched in expression and return a new expression that removed all
// parentheses, no calculation is carried out.
std::string calculateStr(const std::string &s);
std::string evalParenthesesExpression(const std::string &expression) {
std::stack<char> stk;
for (const auto &c : expression) {
if (c == ')') {
std::string str;
while (!stk.empty() && stk.top() != '(') {
str += stk.top();
stk.pop();
}
if (stk.empty()) {
std::cerr << "Error: parentheses not match in expression: "
<< expression << std::endl;
return "";
}
stk.pop(); // pop char `(`
str = calculateStr(std::string(str.rbegin(), str.rend()));
for (const auto &e : str) // push back the result to stk
stk.push(e);
} else {
stk.push(c);
}
}
std::string str;
while (!stk.empty()) { // calculate what remains in stack
if (stk.top() == '(') {
std::cerr << "Error: parentheses not match in expression: "
<< expression << std::endl;
return "";
}
str += stk.top();
stk.pop();
}
str = calculateStr(std::string(str.rbegin(), str.rend()));
return str;
}
// Calculate the expression without parentheses.
std::string calculateStr(const std::string &s) {
// We can do the calculate here in future. The string passed in must not have
// parentheses. Thus we only need to consider associativity and precedence of
// the operators.
// For now, just return the expression.
return s;
}
int main() {
std::cout << evalParenthesesExpression("12+34-56-((78-9)+10)") << std::endl;
std::cout << evalParenthesesExpression("(12+34)-(56-((78-9)+10))") << std::endl;
std::cout << evalParenthesesExpression("((12+34-(56-10)-1") << std::endl;
std::cout << evalParenthesesExpression("12+34)-(56-10)-1") << std::endl;
std::string expression;
std::cin >> expression;
std::cout << evalParenthesesExpression(expression) << std::endl;
return 0;
}