题目
采用分治算法迭代计算最长公共前缀问题(python)
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
编码
编写python文件longestCommonPrefix.py
from typing import List
class Solution(object):
def longestCommonPrefix(self, strs: List[str]) -> str:
def lcp(start, end):
if start == end:
return strs[start]
mid = (start + end) // 2
lcpLeft, lcpRight = lcp(start, mid), lcp(mid + 1, end)
minLength = min(len(lcpLeft), len(lcpRight))
for i in range(minLength):
if lcpLeft[i] != lcpRight[i]:
return lcpLeft[:i]
return lcpLeft[:minLength]
return "" if not strs else lcp(0, len(strs) - 1)
input = ["flower","flow","flight"]
result = Solution().longestCommonPrefix(input)
print(result)
运行过程
运行关键步骤一:
第一次运行到第11行时开始第一轮分治。input0 和input1分入了一组,input2单独成二组,二组暂时观望等待一组计算出结果。
运行关键步骤二:
一组开始递归。flower 和flow逐个字符比较,找到它们的最长公共前缀,为flow。
运行关键步骤三:
分治一组计算结果(flow)出来后 和 分治二组一直在等待的flight进行计算最长公共前缀。
运行关键步骤四:
产生最后的最长公共前缀fl
运行结果:
C:\Users\zyy\AppData\Local\Temp\longestCommonPrefix.py\venv\Scripts\python.exe D:/pythontest/longestCommonPrefix.py
fl
Process finished with exit code 0
附
分治算法简述:
https://leetcode-cn.com/tag/divide-and-conquer/