public class Solution {
public int evalRPN(String[] tokens) {
LinkedList<Integer> ll = new LinkedList<>();
for (int i = 0; i < tokens.length; ++i) {
int value = 0;
String token = tokens[i];
char head = token.charAt(0);
if ((head == '+' || head == '-' || head == '*' || head == '/') && token.length() == 1) {
int num1 = ll.pop();
int num2 = ll.pop();
switch (head) {
case '+': value = num2 + num1; break;
case '-': value = num2 - num1; break;
case '*': value = num2 * num1; break;
case '/': value = num2 / num1; break;
default: value = 0;
}
ll.push(value);
} else {
ll.push(Integer.valueOf(token));
}
}
return ll.remove();
}
}
Description
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are
+
,-
,*
,/
. Each operand may be an integer or another expression.Some examples:
My Solution
代码的 run time 是13 ms (96.97%)。时间复杂度是,空间复杂度是。
Analysis
从左往右扫一遍,将结果保存在stack里,简单题。