LeetCode/最长公共前缀
1. 两两比较
把当前最长公共前缀与每一个字符串比较,并进行更新减小
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);
}
};
2. 全局比较
对每个字符串对应位置字符从前往后进行比较,最长公共前缀逐渐增大
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}
int length = strs[0].size();
int count = strs.size();
for (int i = 0; i < length; ++i) {
char c = strs[0][i];
for (int j = 1; j < count; ++j) {
if (i == strs[j].size() || strs[j][i] != c) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
};
自己写的
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int i=-1;
int maxlen=0;
for(int j=0;j<strs.size();j++)
if(strs[j].size()>maxlen)
maxlen=strs[j].size();
bool flag = true;
char temp;
while(flag){
i++;
if(i==maxlen) break;
temp = strs[0][i];
for(int j=0;j<strs.size();j++) if(strs[j][i]!=temp){flag=false;break;}
}
return strs[0].substr(0,i);
}
};
3. 二分两两比较
递归分治,然后两两提取最长公共前缀,相当于二叉树形的两两比较
二分归并
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}
else {
return longestCommonPrefix(strs, 0, strs.size() - 1);//原函数不具有划分性质,重新写一个
}
}
string longestCommonPrefix(const vector<string>& strs, int start, int end) {
if (start == end) {
return strs[start];
}
else {
int mid = (start + end) / 2;
string lcpLeft = longestCommonPrefix(strs, start, mid);//分治左
string lcpRight = longestCommonPrefix(strs, mid + 1, end);//分治右
return commonPrefix(lcpLeft, lcpRight);//合并分支结果
}
}
string commonPrefix(const string& lcpLeft, const string& lcpRight) {//提取两字符串公共前缀
int minLength = min(lcpLeft.size(), lcpRight.size());
for (int i = 0; i < minLength; ++i) {
if (lcpLeft[i] != lcpRight[i]) {
return lcpLeft.substr(0, i);
}
}
return lcpLeft.substr(0, minLength);
}
};
4. 利用C++内置sort
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return string();
sort(strs.begin(), strs.end());
string st = strs.front(), en = strs.back();
int i, num = min(st.size(), en.size());
for(i = 0; i < num && st[i] == en[i]; i ++);
return string(st, 0, i);
}
};