forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths1.cpp
More file actions
40 lines (40 loc) · 1.14 KB
/
Copy paths1.cpp
File metadata and controls
40 lines (40 loc) · 1.14 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
// OJ: https://leetcode.com/problems/basic-calculator-ii/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
stack<char> ops;
stack<int> nums;
inline int priority(char op) {
if (op == '\0') return 0;
return op == '*' || op == '/' ? 2 : 1;
}
void eval(char op = '\0') {
while (ops.size() && priority(op) <= priority(ops.top())) {
int n = nums.top();
nums.pop();
switch(ops.top()) {
case '+': nums.top() += n; break;
case '-': nums.top() -= n; break;
case '*': nums.top() *= n; break;
case '/': nums.top() /= n; break;
}
ops.pop();
}
ops.push(op);
}
public:
int calculate(string s) {
for (int i = 0, N = s.size(); i < N; ++i) {
if (s[i] == ' ') continue;
if (isdigit(s[i])) {
int n = 0;
while (i < N && isdigit(s[i])) n = n * 10 + (s[i++] - '0');
--i;
nums.push(n);
} else eval(s[i]);
}
eval();
return nums.top();
}
};