A straight method for this problem is the brute force by enumerating the length of the prefix from 0, and ends until we find the longest common prefix.
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
int start=0;
int len=0;
if(strs.size()==0) return "";
int minLen=strs[0].length();
for(int i=0; i<strs.size(); i++){ //An important observation to accelerate the process
if(minLen>strs[i].length())
minLen=strs[i].length();
}
int i;
for(i=0; i<minLen; i++){
for(int j=1; j<strs.size(); j++){
if(strs[j][i]!=strs[j-1][i]){ //break if the condition is not satisfied
len=i-start;
return strs[0].substr(start, len);
}
}
}
len=i-start;
return strs[0].substr(start, len);
}
};
This time complexity is O(m*l) where l is the minimum length of the string, and the space complexity is O(1)