Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. class Solution(object):
  2. def calculate(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6.  
  7. Time O(n)
  8. Space O(n)
  9. 136 ms, faster than 67.45%
  10. """
  11. res = 0
  12. stack = []
  13. # 1 means positive, -1 means negative
  14. # we declare it as an integer because we want to put the +- in the stack too
  15. sign = 1
  16. num = 0
  17. i = 0
  18. while i < len(s):
  19. if s[i].isdigit():
  20. # construct a multi-digits number if any, e.g. "23" = 2*10+3 = 23
  21. j = i
  22. num = 0
  23. while j < len(s) and s[j].isdigit():
  24. num = num*10 + int(s[j])
  25. j += 1
  26. # sum up the intermediate result
  27. res += sign * num
  28. i = j
  29. elif s[i] == '+':
  30. # the next number will be using +
  31. sign = 1
  32. i += 1
  33. elif s[i] == '-':
  34. # the next number will be using -
  35. sign = -1
  36. i += 1
  37. elif s[i] == '(':
  38. # put the intermediate result(from the front) and sign into the stack
  39. stack.append(res)
  40. stack.append(sign)
  41. # since we have put the intermediate result in stack,
  42. # we can reset the things for calculation starting from this (
  43. res = 0
  44. sign = 1
  45. i += 1
  46. elif s[i] == ')':
  47. # last item is the sign we saved for calculation e.g. 1+(2+3) the 1st +
  48. sign = stack.pop()
  49. # previousLevelResult the intermediate result before this level, (xxx)
  50. previousLevelResult = stack.pop()
  51. # sign*res is the result within the current (xxx)
  52. res = previousLevelResult + sign * res
  53. i += 1
  54. else:
  55. i += 1
  56. return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement