@@ -133,39 +133,26 @@ public:
133
133
java:
134
134
135
135
```Java
136
- public class EvalRPN {
137
-
136
+ class Solution {
138
137
public int evalRPN(String[] tokens) {
139
138
Deque<Integer> stack = new LinkedList();
140
- for (String token : tokens) {
141
- char c = token.charAt(0);
142
- if (!isOpe(token)) {
143
- stack.addFirst(stoi(token));
144
- } else if (c == '+') {
145
- stack.push(stack.pop() + stack.pop());
146
- } else if (c == '-') {
147
- stack.push(- stack.pop() + stack.pop());
148
- } else if (c == '*') {
149
- stack.push( stack.pop() * stack.pop());
139
+ for (int i = 0; i < tokens.length; ++i) {
140
+ if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等
141
+ stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理
142
+ } else if ("-".equals(tokens[i])) {
143
+ stack.push(-stack.pop() + stack.pop());
144
+ } else if ("*".equals(tokens[i])) {
145
+ stack.push(stack.pop() * stack.pop());
146
+ } else if ("/".equals(tokens[i])) {
147
+ int temp1 = stack.pop();
148
+ int temp2 = stack.pop();
149
+ stack.push(temp2 / temp1);
150
150
} else {
151
- int num1 = stack.pop();
152
- int num2 = stack.pop();
153
- stack.push( num2/num1);
151
+ stack.push(Integer.valueOf(tokens[i]));
154
152
}
155
153
}
156
154
return stack.pop();
157
155
}
158
- private boolean isOpe(String s) {
159
- return s.length() == 1 && s.charAt(0) <'0' || s.charAt(0) >'9';
160
- }
161
- private int stoi(String s) {
162
- return Integer.valueOf(s);
163
- }
164
-
165
- public static void main(String[] args) {
166
- new EvalRPN().evalRPN(new String[] {"10","6","9","3","+","-11","*","/","*","17","+","5","+"});
167
- }
168
-
169
156
}
170
157
```
171
158
0 commit comments