原题链接
菜狗本菜原思路
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();//求出动态数组的元素个数,不能用sizeof(strs),否则求的实际上是指针大小,是一个常量
int max=strs[0].length();//用length函数求出每个字符串数组所含元素个数
for (int i=0;i<len;i++){
if (strs[i].length()<max)
max=strs[i].length();
//max的值为字符串数组中最短的字符串
}
for (int i=0;i<len;i++){
for (int j=i+1;j<len;j++){
string s=strs[i].substr(0,max);
if (s!=strs[j].substr(0,max)){
max--;
j--;
}
if (max==0)
break;
}
if (max==0)
break;
}
return strs[0].substr(0,max);
}
};
优化后的代码
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}//像这种只剩空串的话直接返回就好
string prefix = strs[0];
int count = strs.size();
for (int i = 1; i < count; ++i) {
prefix = longestCommonPrefix(prefix, strs[i]);
//依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。
if (!prefix.size()) {
break;
}
}
return prefix;
}
//重载函数牛逼
string longestCommonPrefix(const string& str1, const string& str2) {
int length = min(str1.size(), str2.size());
int index = 0;
while (index < length && str1[index] == str2[index]) {
++index;
}
return str1.substr(0, index);
}
};
复杂度分析
时间复杂度:O(mn),其中 m 是字符串数组中的字符串的平均长度,n是字符串的数量。
空间复杂度:O(1)。使用的额外空间复杂度为常数。