forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths5.cpp
More file actions
23 lines (23 loc) · 656 Bytes
/
Copy paths5.cpp
File metadata and controls
23 lines (23 loc) · 656 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// OJ: https://leetcode.com/problems/basic-calculator/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int calculate(string s) {
stack<int> signs;
int n = 0, ans = 0, sign = 1;
signs.push(sign);
for (char c : s) {
if (isdigit(c)) n = 10 * n + (c - '0');
else if (c == '(') signs.push(sign);
else if (c == ')') signs.pop();
else if (c == '+' || c == '-') {
ans += sign * n;
n = 0;
sign = signs.top() * (c == '+' ? 1 : -1);
}
}
return ans + sign * n;
}
};