bracket_match.py 875 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import pytest
  2. def isValid(s: str):
  3. lens = len(s)
  4. if lens % 2 == 1:
  5. return False
  6. dic = {
  7. "(": ")",
  8. "[": "]",
  9. "{": "}"
  10. }
  11. # 栈
  12. list = []
  13. for i in s:
  14. if i in dic.keys():
  15. # 入栈
  16. list.append(i)
  17. else:
  18. # 出栈
  19. if len(list) == 0 or i != dic.get(list[-1]):
  20. list.append(i)
  21. else:
  22. list.pop()
  23. # 栈为空。意为括号都匹配结束
  24. if len(list) == 0:
  25. return True
  26. else:
  27. return False
  28. @pytest.mark.parametrize(
  29. "s, expect",
  30. [
  31. ("()[]", True),
  32. ("(({[])}", False),
  33. ("(]", False),
  34. ("([{}])", True),
  35. ("21[o{00}j]", False)
  36. ]
  37. )
  38. def test_cases(s, expect):
  39. assert isValid(s) == expect