Write a function to find the longest common prefix string amongst an array of strings.
Solution:
We need a template to store the current longest prefix string. The template will be updated in the loop after matching with the new string in strs.
string longestCommonPrefix(vector<string> &strs) {
string tmplt;
if (strs.size() <= 0)
return tmplt;
else {
tmplt = strs[0];
int ind = 1;
while(ind < strs.size() && tmplt != "" ) {
int p = 0;
while(tmplt[p] == strs[ind][p] && p < tmplt.size()) { p++; }
tmplt.erase(p); //reserve previous p elements
++ind;
}
return tmplt;
}
}