Write a function to find the longest common prefix string amongst an array of strings.
思路:先找到前两个的最长前缀,然后拿这个前缀与后面的字符串相比,不断更新最长前缀
代码:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
string res;
res.clear();
if(strs.size()==0) return res;
res=strs[0];
for(int i=1;i<strs.size();i++){
res=longest(res,strs[i]);
}
return res;
}
string longest(string s1, string s2){
string res;
res.clear();
if(s1.size()==0) return res;
if(s2.size()==0) return res;
for(int i=0;i<s1.size();i++){
if(s1[i]==s2[i]){
res+=s1[i];
}
else{
break;
}
}
}
};