[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.
相关文章推荐
- leetcode - Evaluate Reverse Polish Notation
- leetcode Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- leetcode之Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation - LeetCode 150
- [LeetCode] Evaluate Reverse Polish Notation, Solution
- leetcode150 Evaluate Reverse Polish Notation
- leetcode--Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation
- leetcode_c++:栈:Evaluate Reverse Polish Notation(150)
- Evaluate Reverse Polish Notation 求RPN的值@LeetCode
- LeetCode: Evaluate Reverse Polish Notation
- LeetCode OJ:Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation
- 【LeetCode】Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 【LeetCode练习题】Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- LeetCode – Evaluate Reverse Polish Notation