Python 中的最长公共前缀
pythonserver side programmingprogramming更新于 2025/10/31 16:12:17
假设我们有一个数组中的字符串集合。我们必须在数组中的字符串中找到最长公共前缀。这里我们假设所有字符串都是小写字符串。如果没有公共前缀,则返回""。
因此,如果字符串的数组类似于 ["school"、"schedule"、"Scotland"],则最长公共前缀为"sc",因为它存在于所有这些字符串中。
为了解决这个问题,我们将第一个字符串作为 curr,现在从数组中取出每个字符串并逐个读取它们,然后逐个检查 curr 和所取字符串之间的字符。如果它们相同,则转到下一个字符,否则中断循环,并将当前更新为已匹配的子字符串。
让我们看一下实现,以便更好地理解
示例 (Python)
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" current = strs[0] for i in range(1,len(strs)): temp = "" if len(current) == 0: break for j in range(len(strs[i])): if j<len(current) and current[j] == strs[i][j]: temp+=current[j] else: break current = temp return current input_list = ["school","schedule","scotland"] ob1 = Solution() print(ob1.longestCommonPrefix(input_list))
输入
["school","schedule","scotland"]
输出
"sc"
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

