123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- from typing import List
- import pytest
- def commonPrefix(str1, str2):
- flag = 0
- if len(str1) >= len(str2):
- shorter = str2
- longer = str1
- else:
- shorter = str1
- longer = str2
- for i in range(len(shorter)):
- if shorter[i] == longer[i]:
- flag += 1
- else:
- break
- return shorter[0:flag]
- def longestCommonPrefix(strs: List[str]):
- if strs == "":
- return ""
- prefix = strs[0]
- lens = len(strs)
- for i in range(1, lens):
- prefix = commonPrefix(prefix, strs[i])
- if prefix == "":
- break
- return prefix
- @pytest.mark.parametrize(
- "strs, expect",
- [
- (["car", "racecar", "dog"], ""),
- (["flower", "flow", "flight"], "fl"),
- (["ba", "ca", "da"], ""),
- (["aa", ""], ""),
- (["aaa"], "aaa")
- ]
- )
- def test_cases(strs, expect):
- assert longestCommonPrefix(strs) == expect
|