这题我想的复杂度都大于O(n^2)。参考的leetcode网上的答案,采用垂直扫描法,我觉得不错。要注意空数组的情况。
#include <iostream>
#include <string>
#include <vector>
string longestCommonPrefix(vector<string>& strs) {
if (strs.size()==0) return "";
for (int i=0; i<strs[0].size(); i++) {
char c=strs[0].at(i);
for (int j=1; j<strs.size(); j++) {
if (i==strs[j].size())
return strs[0].substr(0,i);
if (c!=strs[j].at(i))
return strs[j].substr(0,i);
}
}
return strs[0];
}
int main()
{
vector<string> strs={"leetcode", "leet", "leetcode2", "le", "lent"};
cout<<longestCommonPrefix(strs);
}