leetcode之Basic Calculator

这道题一开始不太会,各种蛋疼。最近在看数据结构,看到了用栈来解的思路。用python来实现以下吐舌头。代码如下:

class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        import re
        listofnum = []
        listofsym = []
        symbol = ['(', ')', '+', '-']
        #空集
        if len(s) == 0:
            return 0
        #一个字母
        try:
            return int(s)
        except:
            #将所有项分别列出来
            s = re.sub(' ', '', s)
            n = ''
            for i in range(len(s)):
                try:
                    if s[i] in symbol:
                        listofnum.append(int(n))
                        listofsym.append(s[i])                        
                        n = ''
                    elif i == len(s) - 1:
                        n = n + s[i]
                        listofnum.append(int(n))
                    else:
                        n = n + s[i]
                except:
                    listofsym.append(s[i])
                #计算括号
                if s[i] == ')':
                    listofsym.pop()
                    while listofsym[-1] != '(':
                        a = listofnum.pop()
                        b = listofnum.pop()
                        if listofsym[-1] == '-':
                            if listofsym[-2] == '-':
                                listofnum.append(a + b)
                            else:
                                listofnum.append(b - a)
                        else:
                            if listofsym[-2] == '-':
                                listofnum.append(b - a)
                            else:
                                listofnum.append(b + a)
                        listofsym.pop()
                    listofsym.pop()
            #计算括号之外的
            while len(listofsym) != 0:
                a = listofnum.pop()
                b = listofnum.pop()
                try:
                    if listofsym[-1] == '-':
                        if listofsym[-2] == '-':
                            listofnum.append(a + b)
                        else:
                            listofnum.append(b - a)
                    else:
                        if listofsym[-2] == '-':
                            listofnum.append(b - a)
                        else:
                            listofnum.append(b + a)
                    listofsym.pop()
                except:
                    if listofsym[-1] == '-':
                        return b - a
                    else:
                        return a + b
            return listofnum[0]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值