-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path150.逆波兰表达式求值.java
57 lines (54 loc) · 1.25 KB
/
150.逆波兰表达式求值.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* @lc app=leetcode.cn id=150 lang=java
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
class Solution {
public int evalRPN(String[] tokens) {
int[] stack = new int[tokens.length];
int top = -1;
for (String s : tokens) {
if (isOperator(s)) {
int b = stack[top--];
int a = stack[top--];
stack[++top] = calculate(s, a, b);
} else {
stack[++top] = Integer.valueOf(s);
}
}
return stack[0];
}
public int calculate(String s, int a, int b) {
int ans = 0;
switch (s) {
case "+":
ans = a + b;
break;
case "-":
ans = a - b;
break;
case "*":
ans = a * b;
break;
case "/":
ans = a / b;
break;
default:
break;
}
return ans;
}
public boolean isOperator(String s) {
if (
s.equals("+") ||
s.equals("-") ||
s.equals("*") ||
s.equals("/")
) {
return true;
}
return false;
}
}
// @lc code=end