LeetCode Evaluate Reverse Polish Notation

來源:互聯網
上載者:User

標籤:

LeetCode解題之Evaluate Reverse Polish Notation原題

對錶達式的尾碼形式(也稱為逆波蘭運算式)進行計算並返回結果。操作符只有加減乘除四種,運算元為一個整數或者一個運算式。

注意點:

  • 無

例子:

輸入: tokens = [“2”, “1”, “+”, “3”, “*”]

輸出: 9

解題思路

尾碼運算式的形式為運算元1,運算元2,操作符,也就是操作符要進行計算操作的兩個數(或者運算式)在它的前方,所以在遍曆列表的時候,我們要將前面的操作符壓入棧中,當遇到操作符的時候,我們將它對應的運算元彈出並進行計算,計算結果可能是其他動作符的運算元,它原來是一個運算式,我們將該運算式的值計算出來了,所以應該把那個值繼續壓棧,遍曆完整個列表的時候,計算結束。這裡特別要注意的是除法操作,因為給的運算式都是合法的,所以不用考慮除數為零的情況,但這裡的除法操作是針對整數的,會對結果進行去尾操作。對負數與整數的除法操作也與Python內建的計算方式不同,Python計算-1//2結果為-1,而在這裡應該為0,所以要進行特殊的處理。

AC源碼
class Solution(object):    def evalRPN(self, tokens):        """        :type tokens: List[str]        :rtype: int        """        stack = []        for token in tokens:            if token not in ("+", "-", "*", "/"):                stack.append(int(token))            else:                second = stack.pop()                first = stack.pop()                if token == "+":                    stack.append(first + second)                elif token == "-":                    stack.append(first - second)                elif token == ‘*‘:                    stack.append(first * second)                else:                    if first * second < 0:                        stack.append(-(abs(first) // abs(second)))                    else:                        stack.append(first // second)        return stack.pop()if __name__ == "__main__":    assert Solution().evalRPN(["2", "1", "+", "3", "*"]) == 9    assert Solution().evalRPN(["4", "13", "5", "/", "+"]) == 6    assert Solution().evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22

歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來獲得相關源碼。

LeetCode Evaluate Reverse Polish Notation

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.