C#LeetCode刷题之#14-最长公共前缀​​​​​​​(Longest Common Prefix)

问题

 

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3921 访问。

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

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

输出: "fl"

输入: ["dog","racecar","car"]

输出: ""

解释: 输入不存在公共前缀。

说明:所有输入只包含小写字母 a-z 。


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 "".

Input: ["flower","flow","flight"]

Output: "fl"

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.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3921 访问。

public class Program {

    public static void Main(string[] args) {
        var strs = new string[] { "flower", "flow", "flight" };

        var res = LongestCommonPrefix(strs);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static string LongestCommonPrefix(string[] strs) {
        if(strs.Length == 0) return "";
        if(strs.Length == 1) return strs[0];
        var min = int.MaxValue;
        foreach(var item in strs) {
            if(item.Length < min) min = item.Length;
        }
        var index = -1;
        for(var i = 0; i < min; i++) {
            for(var j = 1; j < strs.Length; j++) {
                if(strs[j][i] != strs[0][i]) return strs[0].Substring(0, i);
                else {
                    index = i;
                }
            }
        }
        return strs[0].Substring(0, index + 1);
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3921 访问。

fl

分析:

设数组的长度为 n,单词的最大长度为 m,那么显而易见,以上算法的时间复杂度为: O(m*n) 。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值