772 Basic Calculator III

1. Question

Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open(and closing parentheses), the plus+or minus sign-,non-negativeintegers and empty spaces.
The expression string contains only non-negative integers,+,-,*,/operators , open(and closing parentheses)and empty spaces. 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[-2147483648, 2147483647].
Some examples:
1
"1 + 1" = 2
2
" 6-4 / 2 " = 4
3
"2*(5+5*2)/3+(6/2+8)" = 21
4
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12
Copied!
Note:Do not use theevalbuilt-in library function.

2. Implementation

(1) Stack
1
class Solution {
2
public int calculate(String s) {
3
if (s == null || s.length() == 0) {
4
return 0;
5
}
6
7
Stack<Integer> nums = new Stack();
8
Stack<Character> operators = new Stack();
9
10
int i = 0;
11
int num = 0;
12
int n = s.length();
13
14
while (i < n) {
15
char c = s.charAt(i);
16
17
if (Character.isDigit(c)) {
18
num = c - '0';
19
20
while ((i + 1) < n && Character.isDigit(s.charAt(i + 1))) {
21
num = 10 * num + s.charAt(i + 1) - '0';
22
++i;
23
}
24
nums.push(num);
25
}
26
else if (isOperator(c)) {
27
while (!operators.isEmpty() && hasPrecedence(c, operators.peek())) {
28
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
29
}
30
operators.push(c);
31
}
32
else if (c == '(') {
33
operators.push(c);
34
}
35
else if (c == ')') {
36
while (!operators.isEmpty() && operators.peek() != '(') {
37
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
38
}
39
operators.pop();
40
}
41
++i;
42
}
43
44
while (!operators.isEmpty()) {
45
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
46
}
47
return nums.isEmpty() ? 0 : nums.pop();
48
}
49
50
public boolean isOperator(char c) {
51
return c == '+' || c == '-' || c == '*' || c == '/';
52
}
53
54
public int calculate(char operator, int num1, int num2) {
55
int res = 0;
56
57
switch(operator) {
58
case '+':
59
res = num1 + num2;
60
break;
61
case '-':
62
res = num2 - num1;
63
break;
64
case '*':
65
res = num1 * num2;
66
break;
67
case '/':
68
res = num2 / num1;
69
break;
70
}
71
return res;
72
}
73
74
// check if op2 has higher precendence than op1
75
public boolean hasPrecedence(char op1, char op2) {
76
if (op2 == ')' || op2 == '(') {
77
return false;
78
}
79
80
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
81
return false;
82
}
83
return true;
84
}
85
}
Copied!

3. Time & Space Complexity

Stack: 时间复杂度: O(n), 空间复杂度: O(n)