您的位置:首页 > 编程语言 > C语言/C++

Longest Common Prefix

2015-07-19 23:11 316 查看
一、题目要求

Write a function to find the longest common prefix string amongst an array of strings.

二、代码实现

string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
if(strs.size()==1)
return strs.at(0);
sort(strs.begin(),strs.end(),less<string>());
string tmp1,tmp;
tmp1=strs.at(0);
//tmp2=strs.at(1);
if(tmp1.empty())
return "";
//cout<<tmp1<<" "<<tmp2<<endl;
for(auto i=1;i<=tmp1.size();i++)
{
tmp=tmp1.substr(0,i);
for(auto tmp2=1;tmp2<strs.size();tmp2++ )
{
if(strs[tmp2].find(tmp)==0)
{
continue;
}
else
{
if(i==1)
return "";
else
return tmp1.substr(0,i-1);
}
}
}
return tmp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息