官方答案
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);
}
};
合并為一個函數(shù)
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}
string pre = strs[0];
int count = strs.size();
for(int i=1;i<count;i++){
string cur = strs[i];
int length = min(pre.size(), strs[i].size());
int index = 0;
while (index < length && pre[index] == cur[index]) {
++index;
}
pre = pre.substr(0,index);
if (!pre.size()) {
break;
}
}
return pre;
}
};
思路:先取第一個字符串為公共前綴尸疆,然后和下一個字符串比較侧馅,利用longestCommonPrefix函數(shù)尋找公共前綴并更新仿畸,再與下一個比較食棕,當(dāng)前綴長度為0或比較完成時返回結(jié)果,復(fù)雜度為O(mn)错沽。
- min函數(shù)
- string.substr()
主要功能是復(fù)制子字符串簿晓,要求從指定位置開始,并具有指定的長度千埃。如果沒有指定長度_Count或_Count+_Off超出了源字符串的長度憔儿,則子字符串將延續(xù)到源字符串的結(jié)尾。