forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-calculator_1_AC.cpp
91 lines (84 loc) · 2.27 KB
/
basic-calculator_1_AC.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <functional>
#include <unordered_map>
using std::function;
using std::unordered_map;
class Solution {
public:
Solution() {
fun["+"] = [](int x, int y) {return x + y;};
fun["-"] = [](int x, int y) {return x - y;};
fun["*"] = [](int x, int y) {return x * y;};
fun["/"] = [](int x, int y) {return x / y;};
pre["("] = -1;
int p = 0;
pre["+"] = p;
pre["-"] = p;
++p;
pre["*"] = p;
pre["/"] = p;
++p;
}
int calculate(string s) {
int ls = s.size();
int res = 0;
stack<int> nums;
stack<string> ops;
int i = 0;
string op;
while (i < ls) {
if (s[i] == '+' || s[i] == '-' || s[i] == '*' ||
s[i] == '/') {
op.clear();
op.push_back(s[i++]);
while (!ops.empty() && pre[ops.top()] >= pre[op]) {
calc(nums, ops);
}
ops.push(op);
} else if (s[i] == '(') {
op.clear();
op.push_back(s[i++]);
ops.push(op);
} else if (s[i] == ')') {
while (ops.top() != "(") {
calc(nums, ops);
}
ops.pop();
++i;
} else if (isdigit(s[i])) {
int val = 0;
while (i < ls && isdigit(s[i])) {
val = val * 10 + (s[i] - '0');
++i;
}
nums.push(val);
} else {
++i;
}
}
while (!ops.empty()) {
calc(nums, ops);
}
res = nums.top();
nums.pop();
return res;
}
void calc(stack<int> &nums, stack<string> &ops) {
if (nums.size() < 2 || ops.size() < 1) {
return;
}
string op = ops.top();
ops.pop();
int n2 = nums.top();
nums.pop();
int n1 = nums.top();
nums.pop();
nums.push(fun[op](n1, n2));
}
~Solution() {
fun.clear();
pre.clear();
}
private:
unordered_map<string, function<int(int, int)>> fun;
unordered_map<string, int> pre;
};