[LeetCode] Basic Calculator III

772. Basic Calculator III

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, ‘+’, ‘-‘, ‘*’, ‘/‘ operators, and open ‘(‘ and closing parentheses ‘)’. The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

  • Time : O(n)
  • Space : O(1)
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
class Solution {
int parseNum(string& s, int &i) {
int res = 0;
while(i < s.length() and isdigit(s[i])) {
res = res * 10 + (s[i++] & 0b1111);
}
return res;
}
int parseExpr(string& s, int& i) {
char op = '+';
vector<int> nums;
while(i < s.length() and op != ')') {
int n = s[i] == '(' ? parseExpr(s,++i) : parseNum(s,i);
switch(op) {
case '+': nums.push_back(n); break;
case '-': nums.push_back(-n); break;
case '*': nums.back()*=n; break;
case '/': nums.back()/=n; break;
}
op = s[i++];
}
int res = 0;
for(auto& n : nums) res += n;
return res;
}
public:
int calculate(string s) {
int i = 0;
parseExpr(s,i);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/basic-calculator-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.