Leetcode: Evaluate Reverse Polish Notation

来源:互联网 发布:神户制钢造假 知乎 编辑:程序博客网 时间:2024/05/17 04:25

http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/


Solution in Python:class Solution:    # @param tokens, a list of string    # @return an integer    def evalRPN(self, tokens):        #from collections import deque        q = collections.deque()        for val in tokens:            if val not in ['+', '-', '*', '/']:                q.append(val)            else:                op1 = int(q.pop())                op2 = int(q.pop())                if val == '-':                    result = op2 - op1                elif val == '+':                    result = op2 + op1                elif val == '*':                    result = op1*op2                elif val == '/':                    result = int(op2/float(op1))                q.append(result)        return int(q.pop())

这道比较简单的题目使用了一个stack。在python中list可以很方便地实现stack所以解法里面可以不import collections


0 0
原创粉丝点击