long_common_pre.py 940 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from typing import List
  2. import pytest
  3. def commonPrefix(str1, str2):
  4. flag = 0
  5. if len(str1) >= len(str2):
  6. shorter = str2
  7. longer = str1
  8. else:
  9. shorter = str1
  10. longer = str2
  11. for i in range(len(shorter)):
  12. if shorter[i] == longer[i]:
  13. flag += 1
  14. else:
  15. break
  16. return shorter[0:flag]
  17. def longestCommonPrefix(strs: List[str]):
  18. if strs == "":
  19. return ""
  20. prefix = strs[0]
  21. lens = len(strs)
  22. for i in range(1, lens):
  23. prefix = commonPrefix(prefix, strs[i])
  24. if prefix == "":
  25. break
  26. return prefix
  27. @pytest.mark.parametrize(
  28. "strs, expect",
  29. [
  30. (["car", "racecar", "dog"], ""),
  31. (["flower", "flow", "flight"], "fl"),
  32. (["ba", "ca", "da"], ""),
  33. (["aa", ""], ""),
  34. (["aaa"], "aaa")
  35. ]
  36. )
  37. def test_cases(strs, expect):
  38. assert longestCommonPrefix(strs) == expect