需求
编写一个函数来查找字符串数组中的最长公共前缀。
 如果不存在公共前缀,返回空字符串 “”。
 示例 1:
 输入:strs = [“flower”,“flow”,“flight”]
 输出:“fl”
 示例 2:
 输入:strs = [“dog”,“racecar”,“car”]
 输出:“”
 解释:输入不存在公共前缀。
代码
class Solution():
    def max_common(self,strs):
        if not strs:  # 如果数组为空,则返回空字符串
            return ""
        min_len = min(len(word) for word in strs)  # 找到数组中最短字符串的长度
        for i in range(min_len):  # 遍历最短字符串的长度
            char = strs[0][i]  # 取第一个字符串的当前字符
            for word in strs:  # 遍历所有字符串
                if word[i] != char:  # 如果有任何一个字符串的当前字符与第一个字符串的当前字符不同
                    return strs[0][:i]  # 返回第一个字符串的当前字符之前的部分作为结果
        return strs[0][:min_len]  # 如果遍历完最短字符串的长度,没有找到不同的字符,则返回最短字符串作为结果
if __name__ == '__main__':
    call=Solution()
    strs1 = ["flower", "flow", "flight"]
    strs2 = ["dog", "racecar", "car"]
    print(call.max_common(strs1))
    print(call.max_common(strs2))
 
运行结果



















