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
原问题链接:https://leetcode.com/problems/evaluate-reverse-polish-notation/
?
关于逆波兰表达式的计算,其实是有固定的套路的。它和我们平常的表达式计算不一样,我们一般表达式里,计算符是放在两个操作数的中间,而这里计算符是放在两个操作数的后面。但是这个问题的解决思路还是比较简单的,我们每次碰到数字的时候就将它压入栈中,碰到计算符号时就将栈顶的两个元素弹出来参与计算,并将计算后的结果放到栈里面。
按照这个思路,可以很容易得到如下的代码:
?
public class Solution { public int evalRPN(String[] tokens) { LinkedList<Integer> stack = new LinkedList<>(); for(String str : tokens) { if(str.equals("+")) { stack.push(stack.pop() + stack.pop()); } else if(str.equals("-")) { int second = stack.pop(); stack.push(stack.pop() - second); } else if(str.equals("*")) { int result = stack.pop() * stack.pop(); stack.push(result); } else if(str.equals("/")) { int second = stack.pop(); stack.push(stack.pop() / second); } else { stack.push(Integer.parseInt(str)); } } return stack.peek(); } }
?
leetcode: Evaluate Reverse Polish Notation
原文:http://shmilyaw-hotmail-com.iteye.com/blog/2310239