中级农民
- 积分
- 118
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-6-22
- 最后登录
- 1970-1-1
|
好题,恭喜楼主
- class Solution(object):
- def basicCaculator(self, s):
- """
- :type n: int
- :rtype: List[str]
- """
- num, nums, ops = 0, [0], []
- s = s + '#'
- for i in range(len(s)):
- if s[i] in '0123456789':
- num += num*10 + int(s[i])
- else:
- if i>0 and s[i-1] not in '+-*/()':
- nums.append(num)
- num = 0
- if s[i] in '+-*/':
- if ops and ops[-1] in '*/':
- y, x, op = nums.pop(), nums.pop(), ops.pop()
- nums.append(self.applyOps(x, y, op))
- ops.append(s[i])
- elif s[i]=='(':
- ops.append(s[i])
- elif s[i]==')':
- while ops[-1]!='(':
- y, x, op = nums.pop(), nums.pop(), ops.pop()
- nums.append(self.applyOps(x, y, op))
- ops.pop()
- while ops:
- y, x, op = nums.pop(), nums.pop(), ops.pop()
- nums.append(self.applyOps(x, y, op))
- return nums[-1]
- def applyOps(self, x, y, op):
- if op=='+':
- return x + y
- elif op=='-':
- return x - y
- elif op=='*':
- return x * y
- else:
- if x//y<0 and x%y:
- return x//y+1
- else:
- return x//y
- s = '1*(2-3)'
- so = Solution()
- a = so.basicCaculator(s)
- print(a)
复制代码 |
|