题目:Write a function to find the longest common prefix string amongst an array of strings.
找到字符串的最长公共前缀,方法是先找到前2个字符串的最长公共前缀prefix,再拿prefix作为新的字符串和数组中的下一个字符串比较,如此迭代即可,代码如下:
string longestCommonPrefix(vector<string> &strs)
{
string res;
if(strs.size()<1) return "";
res=strs[0] ;
for(int i=1; i<strs.size(); i++)
{
if(res.length() == 0 || strs[i].length() == 0) return "";
int j=0;
int size=(res.size()>strs[i].size())? strs[i].size():res.size();
for(; j<size; j++)
{
if(strs[i][j]!=res[j])
break;
}
res=res.substr(0,j);
}
return res;
}