[Leetcode Soution]Evaluate Reverse Polish Notation

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


Evaluate a RPN expression is simple with a specific algorithm to deal with.

STACK<NOTATION> stack;
FOR notation IN post-fix-expression:
    IF notation IS NUMBER:
        stack.push(notation)
    IF notation IS OPERATOR:
        b = stack.pop()
        a = stack.pop()
        c = EVALUATE(a, notation, b)
        stack.push(c)
RETURN stack.top()


My Python Solution:

class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        stack = []
        for token in tokens:
            try:
                v = int(token)
                stack.append(v)
            except:
                a = stack.pop()
                b = stack.pop()
                # eval is evil
                c = eval("1. * %d %s %d" % (b, token, a))
                stack.append(int(c))
        return stack[0]

We don't like easy problem, neither do the interviewers. Let's extend the problem to "How to evaluate a infix notation expression with RPN?"

The convert from In-fix to post-fix is a little bit complicated.

STACK<NOTATION> stack;
VECTOR<NOTATION> post-fix-expression;
FOR notation IN in-fix-expression:
    IF notation IS NUMBER OR stack.is_empty() OR notation IS '(':
        stack.push(notation)
    ELIF notation IS ')':
        WHILE st.top() IS NOT '(':
            post-fix-expression.push_back(st.pop())
        st.pop()
    ELSE:
        WHILE !stack.is_empty() AND OP_PRI(notation) > OP_PRI(stack.top()):
            post-fix-expression.push_back(stack.pop());
        stack.push(notation)
WHILE !stack.is_empty():
    post-fix-expression.push_back(stack.pop())
RETURN post-fix-expression

If you are interested, you can try the problem POJ1686( link). It is a full workflow about "in-fix post-fix" conversion and the RPN expression evaluation. Enjoy.


POJ1686 Hint.

The number notations contain only ONE DIGIT, value from 0 to 9. As a result, we can map the variable notation(a, b, c) to the primes larger than 10. It will much simplify the problem.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值