原题目:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串
""
。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
分析:
没想到快速的方法,字符串数组最小为1,假设第一个字符串为公共前缀,依次和后面的去比较,每比较一次,记录下当前的公共前缀,最后就是整字符串数组中最长的公共前缀
代码:
Python3版本
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
#每次比较前临时公共前缀
temp_str = ""
#最后结果的最长公共前缀
common_prefix = strs[0]
n = len(strs)
for i in range(1, n):
#每次索引初始化为0
common_index, d_index = 0, 0
des_str = strs[i]
#满足当前公共前缀和新字符串长度最小的值
while common_index < len(common_prefix) and d_index < len(des_str):
#当前字符为相同即公共,否则跳出进行下一次循环
if common_prefix[common_index] == des_str[d_index]:
temp_str = temp_str + common_prefix[common_index]
else:
break
#索引更新
common_index = common_index + 1
d_index = d_index + 1
#临时公共前缀保存
common_prefix = temp_str
#临时公共前缀清空
temp_str = ""
return common_prefix