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)) -> 6Answer:
[C++]
- class Solution {
- public:
- int evalRPN(vector<string> &tokens) {
- stack<int> numeric;
- for(auto& t : tokens)
- {
- if (isdigit(t[0]) || t.size()>1)
- numeric.push(atoi(t.c_str()));
- else
- {
- int o1, o2;
- o2 = numeric.top();
- numeric.pop();
- o1 = numeric.top();
- numeric.pop();
- switch(t[0])
- {
- case '+':
- numeric.push(o1 + o2);
- break;
- case '-':
- numeric.push(o1 - o2);
- break;
- case '*':
- numeric.push(o1 * o2);
- break;
- case '/':
- numeric.push(o1 / o2);
- break;
- }
- }
- }
- return numeric.top();
- }
- };
[Python]
计算符号在后缀上。可以理解成二叉树的后序遍历(操作符都在父节点上)
- class Solution:
- # @param tokens, a list of string
- # @return an integer
- def operator(self,a,b,op):
- a = int(a)
- b = int(b)
- if op == "+":
- return int(a+b)
- elif op == "-":
- return int(a-b)
- elif op == "*":
- return int(a*b)
- elif op == "/":
- if b == 0:
- return 0
- else:
- return int(float(a)/float(b))
- def evalRPN(self, tokens):
- stack = []
- tl = len(tokens)
- op = ["+","-","*","/"]
- for i in range(tl):
- if tokens[i] in op:
- a = stack.pop()
- b = stack.pop()
- c = self.operator(b,a,tokens[i])
- stack.append(c)
- else:
- stack.append(tokens[i])
- return int(stack[0])
No comments:
Post a Comment