Basic Calculator LeetCode solution in Java

1
class Solution {
2
int idx; // this index traverse the string in one pass, between different level of recursion
3

4
public int calculate(String s) {
5
idx = 0; // Initialization should be here
6
return helper(s);
7
}
8

9
private int helper(String s) {
10
int res = 0, num = 0, preSign = 1, n = s.length();
11
while (idx < n) {
12
char c = s.charAt(idx++);
13
if (c == '(') num = helper(s); // Let recursion solve the sub-problem
14
else if (c >= '0' && c <= '9') num = num * 10 + c - '0';
15
if (c == '+' || c == '-' || c == ')'
16
|| idx == n) { // we need one more calculation when idx == n
17
res += preSign * num;
18
if (c == ')') return res; // end of a sub-problem
19
num = 0;
20
preSign = c == '+' ? 1 : -1;
21
}
22
}
23
return res;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0