题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
# 取第一个字符串作为初始公共前缀
prefix = strs[0]
# 遍历字符串数组,逐个字符比较公共前缀
for s in strs[1:]:
while not s.startswith(prefix):
# 如果当前字符串不以公共前缀开头,则缩短公共前缀
prefix = prefix[:-1]
if not prefix:
# 如果公共前缀已经为空,则直接返回空字符串
return ""
return prefix

