题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串””。

image.png

思路

如果数组长度为0,则返回空字符串””。

以数组中第0个元素作为模板,双指针比较两个字符串的公共元素

  1. common_prefix = ''
  2. for ch1, ch2 in zip(str1, str2):
  3. if ch1 != ch2:
  4. break
  5. else:
  6. common_prefix += ch1

依次遍历字符串数组中的每个字符串,更新最长公共前缀。

  1. class Solution:
  2. def longestCommonPrefix(self, strs: List[str]) -> str:
  3. if len(strs) == 0: return ''
  4. if len(strs) == 1: return strs[0]
  5. common_prefix = strs[0]
  6. for str_ in strs[1:]:
  7. tmp = ''
  8. for ch1, ch2 in zip(common_prefix, str_):
  9. if ch1 != ch2:
  10. break
  11. else:
  12. tmp += ch1
  13. common_prefix = tmp
  14. return common_prefix