算法思想一:横向扫描

解题思路:

用LCP(S1...Sn)表示字符串S1 ... Sn的最长公共前缀
可以得到结论:
                    LCP(S1...Sn) = LCP(LCP(LCP(S1,S2),S3),... Sn)
基于该结论,可以得到一种查找字符串数组中的最长公共前缀的简单方法。依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。
如果在尚未遍历完所有的字符串时,最长公共前缀已经是空串,则最长公共前缀一定是空串,因此不需要继续遍历剩下的字符串,直接返回空串即可。

代码展示:

Python版本
class Solution:
    def longestCommonPrefix(self , strs ):
        # write code here
        if not strs:
            return ""
        
        prefix, count = strs[0], len(strs)
        for i in range(1, count):
            # 递归两两字串对比寻找最长公共前缀
            prefix = self.lcp(prefix, strs[i])
            if not prefix:
                break
        return prefix

    def lcp(self, str1, str2):
        length, index = min(len(str1), len(str2)), 0
        while index < length and str1[index] == str2[index]:
            index += 1
        return str1[:index]

复杂度分析

时间复杂度O(MN):其中 m 是字符串数组中的字符串的平均长度,n 是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次。
空间复杂度O(1):使用的额外空间复杂度为常数

算法思想二:二分查找

解题思路:

最长公共前缀的长度不会超过字符串数组中的最短字符串的长度。用 minLength 表示字符串数组中的最短字符串的长度,则可以在 [0,minLength] 的范围内通过二分查找得到最长公共前缀的长度。每次取查找范围的中间值 mid,判断每个字符串的长度为 mid 的前缀是否相同,如果相同则最长公共前缀的长度一定大于或等于 mid,如果不相同则最长公共前缀的长度一定小于 mid,通过上述方式将查找范围缩小一半,直到得到最长公共前缀的长度。

代码展示:

JAVA版本
import java.util.*;


public class Solution {
    /**
     * 
     * @param strs string字符串一维数组 
     * @return string字符串
     */
    public String longestCommonPrefix (String[] strs) {
        // write code here
        if (strs == null || strs.length == 0) {
            return "";
        }
        int minLength = Integer.MAX_VALUE;
        for (String str : strs) {
            // 获取最短字符串的长度
            minLength = Math.min(minLength, str.length());
        }
        // 二分查找
        int low = 0, high = minLength;
        while (low < high) {
            // 分别对前后两部分进行判断
            int mid = (high - low + 1) / 2 + low;
            if (isCommonPrefix(strs, mid)) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        return strs[0].substring(0, low);
    }
    // 判断长度为 length 的字符是否是strs的共同字串
    public boolean isCommonPrefix(String[] strs, int length) {
        String str0 = strs[0].substring(0, length);
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            String str = strs[i];
            for (int j = 0; j < length; j++) {
                if (str0.charAt(j) != str.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }
}

复杂度分析

时间复杂度O(MNlogM):其中 m 是字符串数组中的字符串的平均长度,n 是字符串的数量。二分查找的迭代执行次数是 O(logm),每次迭代最多需要比较 mn个字符,因此总时间复杂度是O(mnlogm)。
空间复杂度O(1):使用的额外空间复杂度为常数

算法思想三:分治

解题思路:

注意到 LCP 的计算满足结合律,有以下结论:
                            LCP(S1…Sn)=LCP(LCP(S 1…Sk),LCP(Sk+1…Sn))
其中 LCP(S1…Sn) 是字符串 S1…Sn的最长公共前缀,1 < k < n。
基于上述结论,可以使用分治法得到字符串数组中的最长公共前缀。对于问题 LCP(Si⋯Sj),可以分解成两个子问题 LCP(Si…Smid) 与 LCP(Smid+1…Sj),其中 mid= (i+j) / 2。对两个子问题分别求解,然后对两个子问题的解计算最长公共前缀,即为原问题的解。

代码展示:

Python版本
class Solution:
    def longestCommonPrefix(self , strs ):
        # write code here
        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)

复杂度分析

时间复杂度O(MN):其中 m 是字符串数组中的字符串的平均长度,n 是字符串的数量。二分查找的迭代执行次数是 O(logm),每次迭代最多需要比较 mn个字符,因此总时间复杂度是O(mnlogm)。
空间复杂度O(MlogN):其中 m 是字符串数组中的字符串的平均长度,n 是字符串的数量。空间复杂度主要取决于递归调用的层数,层数最大为 logn,每层需要 m 的空间存储返回结果