题目要求:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
题目比较简单,时间复杂度不大,只要考虑遍历即可。
1、如果vector长度为0,或者为1,直接返回。
2、找出最短的string
3、若最短string为空,则直接返回这个空string。
4、否则,对每个string的位置为i的元素,遍历vector每个元素的对应i位置元素,若迭代器到终点,则说明都相同,结果就加入。
5.否则,退出,返回上次得到的最长。
代码如下:
<span style="font-size:14px;">string longestCommonPrefix(vector<string>& strs) {
string ret;
int vlen=strs.size();
//vector 长度为0 或者1 均返回原值
if(vlen==0) return ret;
if(vlen==1)return strs[0];
//求最短的string值
vector<string>::iterator it=strs.begin();
int tmp=(*it).size();
int ishort=tmp;
string sshort=*it;
++it;
while(it!=strs.end())
{
tmp=(*it).size();
if(tmp<ishort)
{
ishort=tmp;
sshort=*it;
}
++it;
}
int len=sshort.length();
if(len==0) return ret;
for(int i=0;i<len;i++)
{
//求最长common prefix,首先遍历vector,与当前char相同就继续比较下一个
for(it=strs.begin();it!=strs.end()&&(*it).at(i)==sshort.at(i);++it);
//迭代器跑到最后,代表有相同元素
if(it==strs.end()) ret+=sshort.at(i);
else break;//否则就结束
}
return ret;
}</span>