Guest User

Untitled

a guest
Nov 23rd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. class Solution(object):
  2. def isValidSerialization(self, preorder):
  3. """
  4. :type preorder: str
  5. :rtype: bool
  6. """
  7. preorder = preorder.split(',')
  8. stack = []
  9. for c in preorder:
  10. if len(stack) > 1 and stack[0] == '#':
  11. return False
  12. while (c == '#') and (len(stack) > 1) and (stack[-1] == '#'):
  13. stack.pop()
  14. stack.pop()
  15. stack.append(c)
  16. return stack == ['#']
  17.  
  18.  
  19. class Solution2(object):
  20. def isValidSerialization(self, preorder):
  21. """
  22. :type preorder: str
  23. :rtype: bool
  24. """
  25. cnt = 1
  26. for node in preorder.split(','):
  27. if cnt == 0:
  28. return False
  29. elif node == '#':
  30. cnt -= 1
  31. else:
  32. cnt += 1
  33. return cnt == 0
  34.  
  35.  
  36. class Solution3(object):
  37. def isValidSerialization(self, preorder):
  38. """
  39. :type preorder: str
  40. :rtype: bool
  41. """
  42. count_to_visit = 1
  43. for c in preorder.split(','):
  44. count_to_visit -= 1
  45. if count_to_visit < 0:
  46. return False
  47. if c != '#':
  48. count_to_visit += 2
  49. return count_to_visit == 0
  50.  
  51.  
  52. if __name__ == "__main__":
  53. s = Solution()
  54.  
  55. preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
  56. assert s.isValidSerialization(preorder) is True
  57.  
  58. preorder = "1,#"
  59. assert s.isValidSerialization(preorder) is False
  60.  
  61. preorder = "9,#,#,1"
  62. assert s.isValidSerialization(preorder) is False
  63.  
  64. preorder = "1,#,#,#,#"
  65. assert s.isValidSerialization(preorder) is False
  66.  
  67. preorder = "9,#,92,#,#"
  68. assert s.isValidSerialization(preorder) is True
Add Comment
Please, Sign In to add comment