
问题
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
输入: [“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.
示例
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种算法实现,以下是这个案例的输出结果:
fl
分析:
设数组的长度为 n,单词的最大长度为 m,那么显而易见,以上算法的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3921。