编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。

示例

输入:strs = ["flower","flow","flight"]

输出:"fl"

解析

1)令最长公共前缀 ans 的值为第一个字符串,进行初始化;

2)遍历后面的字符串,依次将其与 ans 进行比较,相同的追加到临时字符串中,不同则停止比对。

代码示例

def longestCommonPrefix(strs):
    if len(strs) == 0:
        return ''
    ans = strs[0]
    for s in strs[1:]:
        if s == '':
            return ''
        temp = ''
        l = min(len(ans), len(s))
        for i in range(l):
            if ans[i] != s[i]:
                break
            else:
                temp += ans[i]
        ans = temp
    return ans

print(longestCommonPrefix(['', 'a']))

执行用时:32 ms, 在所有 Python3 提交中击败了 93.69% 的用户.

本文为 陈华 原创,欢迎转载,但请注明出处:http://www.ichenhua.cn/read/348