因为是很标准的两个oprand 一个operator 所以很简单
但是注意string compare不能用==!!!要用equals
外加注意-和/的顺序
public class Solution {
public int evalRPN(String[] tokens) {
Stack <Integer> stack = new Stack <Integer> ();
for ( int i = 0; i < tokens.length; i ++ ){
if ( tokens[i].equals("+")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 + op2);
}
else if ( tokens[i].equals("-") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 - op1);
}
else if ( tokens[i].equals("*")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 * op2);
}
else if ( tokens[i].equals("/") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 / op1);
}
else{
stack.push( Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}

本文介绍了一种使用栈数据结构来解析和计算逆波兰表示法(RPN)表达式的Java实现方法。该方法能够处理基本的数学运算符如加、减、乘、除,并通过具体示例代码展示了如何进行操作数和运算符的处理。
254

被折叠的 条评论
为什么被折叠?



