Advertisement
Guest User

Untitled

a guest
May 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. import functools
  2.  
  3. class Solution:
  4. def scoreOfParentheses(self, S: str) -> int:
  5. @functools.lru_cache(maxsize=None)
  6. def compute(s: str) -> int:
  7. if len(s) <= 2:
  8. return 1 if s == "()" else None # rule #1
  9. if s.startswith(")") or s.endswith("("):
  10. return None
  11.  
  12. score = compute(s[1:-1])
  13. if score is not None:
  14. return 2 * score # rule #3
  15.  
  16. for i in range(2, len(s) - 1, 2):
  17. score = compute(s[:i])
  18. if score is None:
  19. continue
  20. score2 = compute(s[i:])
  21. if score2 is None:
  22. continue
  23. return score + score2 # rule #2
  24.  
  25. return compute(S)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement