this is a easy question
the intuition of our method: we should record the max prefix from the first string to the last one.
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
string pre(strs[0]);
// cout<<strs[0]<<endl;
int n=strs.size();
cout<<n<<endl;
int maxl=strs[0].length();
if(n==1)
return pre;
int m;
for(int i=1;i<n;i++)
{
m=strs[i].length();
maxl=min(maxl, m);
for( int j=maxl-1;j>=0;j--)
{
if(pre[j]!=strs[i][j])
{
maxl=j;
}
}
}
return pre.substr(0,maxl);
}
};
-
we should care about the empty vector.
-
using the first string as the longest prefix p _and the length(p) , then exhaustively search every string _s | if s.length()<p.length() (first step) | for i=0-length(p) | | :--- | :--- | | length(p)=s.length() | if(s[i]!=p[i]) break; i is longest prefix |
For improve the speed, we can get the shortest length of those strings firstly. because the longest prefix must be shorter than the shortest string.
exit: Ctrl + ↩
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if ( strs.empty() ) return std::string();
unsigned minSize = strs[0].size();
unsigned strsSize = strs.size();
for (unsigned i=1; i<strsSize; ++i) {
minSize = std::min(minSize, (unsigned)strs[i].size());
}
char c;
unsigned j, k;
for (j=0; j<minSize; ++j) {
c = strs[0][j];
for (k=1; k<strsSize; ++k) {
if ( strs[k][j]!=c ) break;
}
if ( k<strsSize && strs[k][j]!=c ) break;
}
return std::string(strs[0],0,j);
}
};