修改0150逆波兰表达式求值 Java版本

将for循环改为for each,使代码更加简洁。因为循环除了对token进行遍历,i并没有其他用途。
This commit is contained in:
lizhendong128
2022-05-19 11:08:59 +08:00
parent 6c0d4365c6
commit 0b88af0824

View File

@ -136,19 +136,19 @@ java:
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList();
for (int i = 0; i < tokens.length; ++i) {
if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题不能使用==判断字符串是否相等
for (String s : tokens) {
if ("+".equals(s)) { // leetcode 内置jdk的问题不能使用==判断字符串是否相等
stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理
} else if ("-".equals(tokens[i])) {
} else if ("-".equals(s)) {
stack.push(-stack.pop() + stack.pop());
} else if ("*".equals(tokens[i])) {
} else if ("*".equals(s)) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(tokens[i])) {
} else if ("/".equals(s)) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
stack.push(Integer.valueOf(tokens[i]));
stack.push(Integer.valueOf(s));
}
}
return stack.pop();