Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. class Solution(object):
  2. def calculate(self, s):
  3. """
  4. Time O(n^2) because we have to find the correspondign closing parenthesis for recursion
  5. Space O(n)
  6. 204 ms, faster than 7.41%
  7. """
  8. if len(s) == 0:
  9. return 0
  10. stack = []
  11. sign = '+'
  12. num = 0
  13. i = 0
  14. while i < len(s):
  15. c = s[i]
  16. if c.isdigit():
  17. num = num*10+int(c)
  18.  
  19. if c == '(':
  20. # find the corresponding ")"
  21. pCnt = 0
  22. end = 0
  23. clone = s[i:]
  24. while end < len(clone):
  25. if clone[end] == '(':
  26. pCnt += 1
  27. elif clone[end] == ')':
  28. pCnt -= 1
  29. if pCnt == 0:
  30. break
  31. end += 1
  32. # do recursion to calculate the sum within the next (...)
  33. num = self.calculate(s[i+1:i+end])
  34. i += end
  35.  
  36. if i + 1 == len(s) or (c == '+' or c == '-' or c == '*' or c == '/'):
  37. if sign == '+':
  38. stack.append(num)
  39. elif sign == '-':
  40. stack.append(-num)
  41. elif sign == '*':
  42. stack[-1] = stack[-1]*num
  43. elif sign == '/':
  44. stack[-1] = int(stack[-1]/float(num))
  45. sign = c
  46. num = 0
  47. i += 1
  48.  
  49. return sum(stack)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement