mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
修改0150逆波兰表达式求值 Java版本
将for循环改为for each,使代码更加简洁。因为循环除了对token进行遍历,i并没有其他用途。
This commit is contained in:
@ -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();
|
||||
|
Reference in New Issue
Block a user