方法1: stack。还是比较容易想到stack的,因为是reverse polish notion,其实这就是postfix表达式,然后还约等于tree里面的postorder traversal。时间复杂n,空间复杂n。
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
stack.push(tokens[0]);
for(int i = 1; i < tokens.length; i++){
String curr = tokens[i];
stack.push(curr);
if(curr.equals("+")){
stack.pop();
int d1 = Integer.parseInt(stack.pop());
int d2 = Integer.parseInt(stack.pop());
String s = String.valueOf(d2 + d1);
stack.push(s);
}else if(curr.equals("-")){
stack.pop();
int d1 = Integer.parseInt(stack.pop());
int d2 = Integer.parseInt(stack.pop());
String s = String.valueOf(d2 - d1);
stack.push(s);
}else if(curr.equals("*")){
stack.pop();
int d1 = Integer.parseInt(stack.pop());
int d2 = Integer.parseInt(stack.pop());
String s = String.valueOf(d2 * d1);
stack.push(s);
}else if(curr.equals("/")){
stack.pop();
int d1 = Integer.parseInt(stack.pop());
int d2 = Integer.parseInt(stack.pop());
String s = String.valueOf(d2 / d1);
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}
}
总结:
- 无