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
My Answer:
public class Solution {
public int evalRPN(String[] tokens) {
LinkedList<Integer> list = new LinkedList<Integer>();
Integer value = new Integer(0);
Integer temp = new Integer(0);
for(String str : tokens){
switch(str){
case "+":
value = list.pop() + list.pop();
list.push(value);
break;
case "-":
temp = list.pop();
value = list.pop() - temp;
list.push(value);
break;
case "*":
value = list.pop() * list.pop();
list.push(value);
break;
case "/":
temp = list.pop();
value = list.pop() / temp;
list.push(value);
break;
default:
list.push(Integer.valueOf(str));
break;
}
}
return list.pop().intValue();
}
}
题目来源: https://oj.leetcode.com/

本文介绍了一种解决逆波兰表达式求值问题的方法。利用栈数据结构处理加减乘除运算,通过遍历字符串数组解析表达式并计算结果。示例展示了如何将输入的逆波兰表达式转换为相应的数学计算。

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



