-
Notifications
You must be signed in to change notification settings - Fork 1
/
150.逆波兰表达式求值.java
90 lines (88 loc) · 2.21 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* @lc app=leetcode.cn id=150 lang=java
*
* [150] 逆波兰表达式求值
*
* https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/description/
*
* algorithms
* Medium (45.16%)
* Likes: 72
* Dislikes: 0
* Total Accepted: 17.7K
* Total Submissions: 37.7K
* Testcase Example: '["2","1","+","3","*"]'
*
* 根据逆波兰表示法,求表达式的值。
*
* 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
*
* 说明:
*
*
* 整数除法只保留整数部分。
* 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
*
*
* 示例 1:
*
* 输入: ["2", "1", "+", "3", "*"]
* 输出: 9
* 解释: ((2 + 1) * 3) = 9
*
*
* 示例 2:
*
* 输入: ["4", "13", "5", "/", "+"]
* 输出: 6
* 解释: (4 + (13 / 5)) = 6
*
*
* 示例 3:
*
* 输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
* 输出: 22
* 解释:
* ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
* = ((10 * (6 / (12 * -11))) + 17) + 5
* = ((10 * (6 / -132)) + 17) + 5
* = ((10 * 0) + 17) + 5
* = (0 + 17) + 5
* = 17 + 5
* = 22
*
*/
// @lc code=start
class Solution {
public int evalRPN(String[] tokens) {
int num1 = 1;
int num2 = 1;
int result = 0;
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if ("+-*/".contains(token)) {
num2 = stack.pop();
num1 = stack.pop();
switch (token) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
stack.push(result);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}
// @lc code=end