Leetcode: Longest Common Prefix

题目: Write a function to find the longest common prefix string amongst an array of strings. 即求给定的一组字符串的公共前缀。

思路分析: 一个一个寻找前缀,,先比较第一个和第二个,找到公共前缀,然后公共前缀和第三个比较,寻找公共前缀,以此类推。

C++参考代码:

class Solution{public:string longestCommonPrefix(vector<string> &strs){if (strs.empty()){return “”;}string common = strs[0];vector<string>::size_type size = strs.size();(int i = 1; i < size; i++){length = min(common.length(), strs[i].length());count = 0;for (int j = 0; j < length; j++){//如果两个字符相等count++if (strs[i][j] == common[j]){count++;}//如果两个字符不相等直接退出内层循环else{break;}}//将common和strs[i]的共同前缀保存在common中,进行下一个字符的比较common = common.substr(0, count);}return common;}};

C#参考代码:

{public string LongestCommonPrefix(string[] strs){if (strs == null || strs.Length == 0){return string.Empty;}string common = strs[0];int length = 0;int count = 0;for (int i = 1; i < strs.Length; i++){length = Math.Min(common.Length, strs[i].Length);count = 0;for (int j = 0; j < length; j++){if (strs[i][j] == common[j]){count++;}else{break;}}common = common.Substring(0, count);}return common;}}

Python参考代码:

:size = len(strs)if not strs or size == 0:return “”common = strs[0]length = 0count = 0for i in range(1, size):length = min(len(common), len(strs[i]))count = 0for j in range(length):if strs[i][j] == common[j]:count += 1else:breakcommon = common[0: count]return common

我喜欢出发。凡是到达了的地方,

Leetcode: Longest Common Prefix

相关文章:

你感兴趣的文章:

标签云: