题目描述
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:
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
评估逆波兰式算术表达式的值。
有效的运算符是+, - ,*,/。每个操作数可以是整数或另一种表达。
解析思路
本题利用堆栈来解决,依次扫描每个字符,如果是数字就压入堆栈,遇到运算符,就从堆栈弹出两个数字进行运算,并将运算的结果压入堆栈。最后堆栈的数字即为最终结果。
AC代码
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
int returnValue = 0;
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for (String t : tokens) {
if (!operators.contains(t)) {
stack.push(t);
}else {
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int index = operators.indexOf(t);
switch (index) {
case 0:
stack.push(String.valueOf(a + b));
break;
case 1:
stack.push(String.valueOf(b - a));
break;
case 2:
stack.push(String.valueOf(a * b));
break;
case 3:
stack.push(String.valueOf(b / a));
break;
}
}
}
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
}
本文介绍了一种使用栈来解析逆波兰表达式的方法。通过遍历表达式中的每个元素,数字被压入栈中,遇到运算符则从栈中取出两个数字进行计算并将结果重新压入栈中。最后栈顶的元素即为表达式的值。
309

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



