Problem:
Write a function to find the longest common prefix string amongst an array of strings.
Analysis:
Find the shortest string in the vector. Compare this one with other strings. If it is not a prefix of some string in the vector, use its prefix (for a length looping from its size to 0) to replace the original string. This is valid, because a common prefix cannot be longer than the shortest string in the vector.
We do not repeat previous comparisons, since a prefix of the shortest string must be the common prefix of other strings. Then, the running time is O(kn), where k the size of longest common prefix.
Solutions:
C++:
string longestCommonPrefix(vector<string> &strs) {
if(strs.empty())
return "";
int minIndex = 0;
int minSize = strs[minIndex].size();
for(int i = 0; i < strs.size(); ++i)
if(strs[i].size() < minSize) {
minIndex = i;
minSize = strs[minIndex].size();
}
string prefix = strs[minIndex];
int prefixLen = prefix.size();
for(int i = 0; i < strs.size(); ++i) {
if(i == minIndex)
continue;
if(strs[i].substr(0, prefixLen) != prefix.substr(0, prefixLen))
for(int j = 1; j <= prefixLen; ++j)
if(j == prefixLen)
return "";
else if(strs[i].substr(0, prefixLen - j) == prefix.substr(0, prefixLen - j)) {
prefixLen -= j;
break;
}
}
return prefix.substr(0, prefixLen);
}
Java:
Python: