Skip to content

Latest commit

 

History

History
42 lines (41 loc) · 1.15 KB

227.md

File metadata and controls

42 lines (41 loc) · 1.15 KB

解法一

  • 80ms
  • 82%
class Solution:
    def calculate(self, s: str) -> int:
        nums, ops = [],[]
        i = 0
        opSet = set(["+", "-", "*", "/"])
        opMD = set(["*", "/"])
        for j in range(i,len(s)):
            if s[j] in opSet:
                tmpNum = int(s[i:j])
                if len(ops)>0 and ops[-1] in opMD:
                    if ops[-1] == "*":
                        nums[-1] = nums[-1]*tmpNum
                    else:
                        nums[-1] = nums[-1]//tmpNum
                    ops.pop()
                else:
                    nums.append(tmpNum)
                ops.append(s[j])
                i = j+1
        nums.append(int(s[i:]))
        if len(ops)>0 and ops[-1] in opMD:
            tmpNum = nums.pop()
            if ops[-1] == "*":
                nums[-1] = nums[-1]*tmpNum
            else:
                nums[-1] = nums[-1]//tmpNum
            ops.pop()
        idx = 0
        ans = nums[0]
        for idx in range(0,len(nums)-1):
            op = ops[idx]
            if op=="+":
                ans += nums[idx+1]
            else:
                ans -= nums[idx+1]
        return ans