水平扫描法。容易想到,但是效率不行。
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
int i=0;
string res;
while(i<strs[0].size()){
char c=strs[0][i];
for(auto str:strs){
if(c!=str[i])
return res;
}
res+=c;
++i;
}
return res;
}
分治法,有点像归并排序
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
return longestCommonPrefix(strs,0,strs.size()-1);
}
string longestCommonPrefix(vector<string>& strs,int left,int right) {
if(left==right)
return strs[left];
else{
int mid=(left+right)/2;
string leftRes = longestCommonPrefix(strs,left,mid);
string rightRes = longestCommonPrefix(strs,mid+1,right);
return CommonPrefix(leftRes,rightRes);
}
}
string CommonPrefix(string leftStr, string rightStr){
int minSize=min(leftStr.size(),rightStr.size());
for(int i=0;i<minSize;++i)
if(leftStr[i]!=rightStr[i])
return leftStr.substr(0,i);
return leftStr.substr(0,minSize);
}
};