假设我们在数组中有一组字符串。我们必须在数组的字符串中找到最长的公共前缀。在这里,我们假设所有字符串都是小写字符串。如果没有通用前缀,则返回“”。
因此,如果字符串的数组类似于[“ school”,“ schedule”,“ Scotland”],则最长公共前缀为“ sc”,因为在所有这些字符串中都存在。
为了解决这个问题,我们将第一个字符串作为curr,现在从数组中取出每个字符串,然后逐个字符读取它们,并逐一检查curr和所取字符串之间的字符。如果它们相同,则转到下一个字符,否则中断循环,并将curr更新为已匹配的子字符串。
让我们看一下实现以获得更好的理解
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"