题目表述:
编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。
输入:strs = [“flower”,“flow”,“flight”] 输出:“fl”
输入:strs = [“dog”,“racecar”,“car”] 输出:"" 解释:输入不存在公共前缀。
解题思路:
使用递归,以此从容器中取出一个string,并和后一个string比较,得出公共前缀。
class Solution {
public:
string longest(string& strs1,string& strs2){
string temp="";
string::iterator p1,p2,p3,p4;
p1=strs1.end();
p2=strs1.begin();
p3=strs2.end();
p4=strs2.begin();
while(p2!=p1&&p4!=p3){
if(*p2==*p4){
temp=temp+*p2;
}
else{
break;
}
p2++;
p4++;
}
return temp;
}
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0){
return "";
}
string temp="";
int i=0;
while(i<strs.size()){
if(i==0){
temp=longest(strs.at(0),strs.at(i));
}
else{
temp=longest(temp,strs.at(i));
}
i++;
}
return temp;
}
};
|