14. Longest Common Prefix

14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string “”.

Example 1:

Input: [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Think and method

I. Comparative reference method
We can set the first element as a baseline reference, compare the reference element with the next element in turn, and keep updating the baseline until the baseline and all elements satisfy the condition for the longest common prefix.
We use strings.Index(k,result) to help us implement. Only when it is not equal to zero, we cut off the last element in the current reference element, and then compare it further until it becomes 0, which means that we have obtained the longest common prefix from the comparison between the reference element and all the elements

Time complexity: O(nm) where m is the average length of the strings in the string array and n is the number of strings.
Space complexity: O(1)

2、Divide and conquer
Inspiration from official documents
According to the above formula, we can split the original string into two subproblems, if the whole string is named LCP(Si…Sj), the left substring is LCP(Si…Smid), the substring on the right is LCP(Smid…Sj),mid=(I +j)/2, solve respectively, and then find the longest common prefix for the solution of the two subproblems.

Time complexity: O(mn), where m is the average length of a string in an array of strings, and n is the number of strings.
Space complexity: O(mlogn)

Others
,of course, we can also use some of the more general train of thought, also is feasible in the subject, for example: longitudinal scanning, once upon a time in the future to iterate through all the columns of the string, the elements of the comparison of each column are the same, if continues to traverse the same, otherwise, this column before the part has been a public prefix, and discuss the special case of an empty set, its complexity of time and space, are also considerable

Time complexity: O(mn)
Space complexity: O(1)

Code:
1、

func longestCommonPrefix(strs []string) string {
    if len(strs) == 0 {
        return ""
    }

    result := strs[0]
    for _,k := range strs {
        for strings.Index(k,result) != 0 {
              if len(strs) == 0 {
                 return ""
                   }       
            result = result[:len(result) - 1]
        }
    }
    return result
}

2、

func longestCommonPrefix(strs []string) string {
    if len(strs) == 0 {
        return ""
    }
    var lcp func(int, int) string
    //lcp func
    lcp = func(start, end int) string {
        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))
          //left compare with right
         for i := 0; i < minLength; i++ {
            if lcpLeft[i] != lcpRight[i] {
                return lcpLeft[:i]
            }
        }
        return lcpLeft[:minLength]
    }
    return lcp(0, len(strs)-1)
}

func min(x, y int) int {
    if x < y {
        return x
    }
    return y
}

Test:
Example 1:

Input: [“flower”,“flow”,“flight”]
在这里插入图片描述

Example 2:

Input: [“dog”,“racecar”,“car”]
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值