您的位置:首页 > 编程语言 > Lua

[Leetcode Soution]Evaluate Reverse Polish Notation

2014-03-18 14:11 218 查看
["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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息