mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -133,39 +133,26 @@ public:
|
|||||||
java:
|
java:
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
public class EvalRPN {
|
class Solution {
|
||||||
|
|
||||||
public int evalRPN(String[] tokens) {
|
public int evalRPN(String[] tokens) {
|
||||||
Deque<Integer> stack = new LinkedList();
|
Deque<Integer> stack = new LinkedList();
|
||||||
for (String token : tokens) {
|
for (int i = 0; i < tokens.length; ++i) {
|
||||||
char c = token.charAt(0);
|
if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等
|
||||||
if (!isOpe(token)) {
|
stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理
|
||||||
stack.addFirst(stoi(token));
|
} else if ("-".equals(tokens[i])) {
|
||||||
} else if (c == '+') {
|
|
||||||
stack.push(stack.pop() + stack.pop());
|
|
||||||
} else if (c == '-') {
|
|
||||||
stack.push(-stack.pop() + stack.pop());
|
stack.push(-stack.pop() + stack.pop());
|
||||||
} else if (c == '*') {
|
} else if ("*".equals(tokens[i])) {
|
||||||
stack.push(stack.pop() * stack.pop());
|
stack.push(stack.pop() * stack.pop());
|
||||||
|
} else if ("/".equals(tokens[i])) {
|
||||||
|
int temp1 = stack.pop();
|
||||||
|
int temp2 = stack.pop();
|
||||||
|
stack.push(temp2 / temp1);
|
||||||
} else {
|
} else {
|
||||||
int num1 = stack.pop();
|
stack.push(Integer.valueOf(tokens[i]));
|
||||||
int num2 = stack.pop();
|
|
||||||
stack.push( num2/num1);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return stack.pop();
|
return stack.pop();
|
||||||
}
|
}
|
||||||
private boolean isOpe(String s) {
|
|
||||||
return s.length() == 1 && s.charAt(0) <'0' || s.charAt(0) >'9';
|
|
||||||
}
|
|
||||||
private int stoi(String s) {
|
|
||||||
return Integer.valueOf(s);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
new EvalRPN().evalRPN(new String[] {"10","6","9","3","+","-11","*","/","*","17","+","5","+"});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user